Guest User

Untitled

a guest
Jan 13th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.80 KB | None | 0 0
  1. package dbConnect;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.PreparedStatement;
  5. import java.sql.ResultSet;
  6. import java.sql.Statement;
  7.  
  8. public class dbConnect {
  9.  
  10. private Connection conn;
  11. private Statement stmt;
  12. private PreparedStatement pstmt;
  13. private ResultSet rs;
  14.  
  15.  
  16. /* 세팅 입력값 */
  17. private static final String dbDriver = "org.mariadb.jdbc.Driver";
  18. private static final String dbtConnectionURL = "jdbc:mysql://localhost:3306/dbName";
  19. private static final String dbUserId = "";
  20. private static final String dbUserPassword = "";
  21.  
  22.  
  23. public void dbDisconn() {
  24. try {
  25. if(rs != null) rs.close();
  26. System.out.println("rs close 완료");
  27. if(stmt != null) stmt.close();
  28. System.out.println("stmt close 완료");
  29. if(conn != null) conn.close();
  30. System.out.println("conn close 완료");
  31. } catch (Exception e2) {
  32. // TODO: handle exception
  33. }
  34. }
  35.  
  36. public void insertDBSong(String artist, String title) {
  37. try {
  38. // 3. 열기
  39. stmt = conn.createStatement();
  40.  
  41. String insert = "";
  42. insert = "INSERT INTO chart";
  43. insert += " VALUES ('1',\' " + title + " \', \'"+ artist +" \')";
  44. pstmt = conn.prepareStatement(insert);
  45. pstmt.execute(insert);
  46. boolean flag = stmt.execute(insert);
  47. if (flag) {
  48. System.out.println("입력완료");
  49. }
  50. } catch (Exception e) {
  51. System.out.println("처리 오류 : " + e);
  52. }
  53. }
  54.  
  55. public void getDBSong() {
  56. try {
  57. // 3. 열기
  58. stmt = conn.createStatement();
  59. // 4. 자료 읽기
  60. /**자료 한개 읽어오기**/
  61. rs = stmt.executeQuery("select * from chart");
  62. // sql문장을 실행하고 re에 저장
  63.  
  64. rs.next();
  65. // Record pointer 이동 : Rec Pointer가 있는 지점 자료만 참조 가능 레코드는 한줄씩(row)만 읽어올수 있음
  66. // Record pointer의 처음 위치는 0번째이기 때문에 next() 로 1번째 레코드로 이동해야 첫번째 자료를 읽어올수있음
  67.  
  68. String title = rs.getString("title");
  69. String artist = rs.getString("artist");
  70.  
  71. // 읽어온 row에서 각 컬럼명으로 값을 찾아서 변수에 저장
  72.  
  73. System.out.println("자료 한줄 읽어오기");
  74. System.out.println(title + " " + artist + " " );
  75.  
  76. /**자료 여러개 읽어오기**/
  77. System.out.println("\n 자료 여러개 읽어오기");
  78. String sql = "select title as 노래제목, artist as 가수, num from chart";
  79.  
  80. // rs = stmt.executeQuery(sql);
  81. /*
  82. while(rs.next()) {
  83. // rs.next()는 re.next() == true 와 같은 뜻
  84. // rs.next()가 존재할때까지 즉, 한줄 한줄 읽어오면서 자료가 존재하면 계속 반복
  85. String code2 = rs.getString("코드");
  86. // 칼럼에 별명을 설정해주면 불러올때 별명을 써야한다 안그럴시 부적합한 열 이름오류
  87.  
  88. String sang2 = rs.getString(2);
  89. // 읽어온 컬럼 순서에 맞춰서 컬럼명 대신 순서를 넣어도 읽어올수있다.
  90.  
  91. int su2 = rs.getInt("su");
  92. // sangdata 테이블의 dan의 데이터형은 int 이지만 계산이 필요하지 않을때는 그냥 String로 불러와도 된다.
  93. // 즉, DB의 변수형과 java의 변수형을 일치하지 않아도 된다.
  94. String dan2 = rs.getString("dan");
  95. System.out.println(code2 + " " + sang2 + " " + su2 + " " + dan2);
  96. }
  97. */
  98.  
  99. /**전체 자료 수 출력**/
  100. System.out.println("\n 전체 자료수 출력");
  101. sql = "select count(*) from chart";
  102. rs = stmt.executeQuery(sql);
  103. rs.next();
  104. System.out.println("건수 : " + rs.getInt(1));
  105. String insert = "INSERT INTO chart VALUES ('3','I Believe', '신승훈')";
  106. stmt.execute(insert);
  107. } catch (Exception e) {
  108. System.out.println("처리 오류 : " + e);
  109. }
  110. }
  111. public dbConnect() {
  112.  
  113. // 1. Driver 로딩
  114. try {
  115. Class.forName(dbDriver);
  116. } catch (Exception e) {
  117. System.out.println("로딩 실패");
  118. return;
  119. }
  120.  
  121. // 2. DB와 연결 (cmd에서 '-mysql -u root -p ' 한것과 같다)
  122. try {
  123. conn = DriverManager.getConnection(dbtConnectionURL, dbUserId, dbUserPassword);
  124. System.out.println("연결성공!");
  125. //conn = DriverManager.getConnection("jdbc:mysql://ip주소:포트번호/db명", "id", "pw");
  126. //mariadb는 mysql에서 나왔기때문에 같은 드라이버를 쓴다.
  127.  
  128. } catch (Exception e) {
  129. System.out.println("연결 실패 : " + e);
  130. }
  131.  
  132. try {
  133. // 3. 열기
  134. stmt = conn.createStatement();
  135. // 4. 자료 읽기
  136. //**자료 한개 읽어오기**//
  137. rs = stmt.executeQuery("select * from chart");
  138. // sql문장을 실행하고 re에 저장
  139.  
  140. rs.next();
  141. // Record pointer 이동 : Rec Pointer가 있는 지점 자료만 참조 가능 레코드는 한줄씩(row)만 읽어올수 있음
  142. // Record pointer의 처음 위치는 0번째이기 때문에 next() 로 1번째 레코드로 이동해야 첫번째 자료를 읽어올수있음
  143.  
  144. String title = rs.getString("title");
  145. String artist = rs.getString("artist");
  146.  
  147. // 읽어온 row에서 각 컬럼명으로 값을 찾아서 변수에 저장
  148.  
  149. System.out.println("자료 한줄 읽어오기");
  150. System.out.println(title + " " + artist + " " );
  151.  
  152. //**자료 여러개 읽어오기**//*
  153. System.out.println("\n 자료 여러개 읽어오기");
  154. String sql = "select title as 노래제목, artist as 가수, num from chart";
  155.  
  156. // rs = stmt.executeQuery(sql);
  157. while(rs.next()) {
  158. // rs.next()는 re.next() == true 와 같은 뜻
  159. // rs.next()가 존재할때까지 즉, 한줄 한줄 읽어오면서 자료가 존재하면 계속 반복
  160. String code2 = rs.getString("코드");
  161. // 칼럼에 별명을 설정해주면 불러올때 별명을 써야한다 안그럴시 부적합한 열 이름오류
  162.  
  163. String sang2 = rs.getString(2);
  164. // 읽어온 컬럼 순서에 맞춰서 컬럼명 대신 순서를 넣어도 읽어올수있다.
  165.  
  166. int su2 = rs.getInt("su");
  167. // sangdata 테이블의 dan의 데이터형은 int 이지만 계산이 필요하지 않을때는 그냥 String로 불러와도 된다.
  168. // 즉, DB의 변수형과 java의 변수형을 일치하지 않아도 된다.
  169. String dan2 = rs.getString("dan");
  170. System.out.println(code2 + " " + sang2 + " " + su2 + " " + dan2);
  171. }
  172. //**전체 자료 수 출력**//
  173. System.out.println("\n 전체 자료수 출력");
  174. sql = "select count(*) from chart";
  175. rs = stmt.executeQuery(sql);
  176. rs.next();
  177. System.out.println("건수 : " + rs.getInt(1));
  178. String insert = "INSERT INTO chart VALUES ('3','I Believe', '신승훈')";
  179. stmt.execute(insert);
  180. } catch (Exception e) {
  181. System.out.println("처리 오류 : " + e);
  182. } finally {
  183. // 5. 연결 끊기 - 작업이 끝나면 닫아주어야 한다
  184. try {
  185. if(rs != null) rs.close();
  186. if(stmt != null) stmt.close();
  187. if(conn != null) conn.close();
  188.  
  189. } catch (Exception e2) {
  190. // TODO: handle exception
  191. }
  192. }
  193. }
  194.  
  195. public static void main(String[] args) {
  196. new dbConnect();
  197. }
  198. }
Add Comment
Please, Sign In to add comment