暂无描述

MariaDBSelect.java 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package kr.co.swh.lecture.database.java;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7. /**
  8. * <pre>
  9. * kr.co.swh.lecture.database.java
  10. * MariaDBSelect.java
  11. *
  12. * 설명 :데이터베이스 검색 예제
  13. * </pre>
  14. *
  15. * @since : 2017. 10. 26.
  16. * @author : tobby48
  17. * @version : v1.0
  18. */
  19. public class MariaDBSelect {
  20. static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
  21. static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/market";
  22. static final String USERNAME = "root";
  23. static final String PASSWORD = "xxxxxxx";
  24. public static void main(String[] args) {
  25. Connection connection = null;
  26. Statement statement = null;
  27. try{
  28. Class.forName(JDBC_DRIVER);
  29. connection = DriverManager.getConnection(DB_URL,USERNAME,PASSWORD);
  30. System.out.println("MariaDB 연결.");
  31. statement = connection.createStatement();
  32. // insert
  33. boolean result = statement.execute("insert into employees(name,c2) values('가준', v2);");
  34. // boolean result = statement.execute(String.format("insert into a(c1,c2) values(%d, %s);", v1, v2));
  35. if(result) System.out.println("ResultSet 값 있다.");
  36. else System.out.println("업데이트 된 행이 있거나 리턴되는 값이 없는 경우");
  37. // update
  38. // int result = statement.executeUpdate("update a set c1 = v1;"); // result = 업데이터된 행의 숫자
  39. // if(result > 0) System.out.println("정상처리");
  40. // else System.out.println("비정상처리");
  41. // select
  42. ResultSet rs = statement.executeQuery("SELECT * FROM employees;");
  43. while(rs.next()){
  44. int employee_id = rs.getInt("employee_id");
  45. String name = rs.getString("name");
  46. double hourly_pay = rs.getDouble("hourly_pay");
  47. long employee_contact = rs.getLong("employee_contact");
  48. System.out.println("employee_id : " + employee_id);
  49. System.out.println("name: " + name);
  50. System.out.println("hourly_pay: " + hourly_pay);
  51. System.out.println("employee_contact: " + employee_contact);
  52. System.out.println(rs.getInt(1)); // 첫번 째 열
  53. }
  54. rs.close();
  55. }catch(SQLException se1){
  56. se1.printStackTrace();
  57. }catch(Exception ex){
  58. ex.printStackTrace();
  59. }finally{
  60. try{
  61. if(statement!=null) statement.close();
  62. if(connection!=null) connection.close();
  63. }catch(SQLException se2){
  64. }
  65. }
  66. System.out.println("MariaDB 연결종료.");
  67. }
  68. }