Java Dao操作数据库实例

    1. package com.zykj.hbase.back.dao;
    2. import com.zykj.hbase.back.utils.JdbcUtil;
    3. import org.junit.Test;
    4. import javax.sql.DataSource;
    5. import java.sql.*;
    6. import java.util.ArrayList;
    7. import java.util.List;
    8. /**
    9. * description
    10. *
    11. * @author ${user}
    12. * @Time 2019-04-08
    13. */
    14. public class DaoImp implements Dao {
    15. // JDBC driver name and database URL
    16. // static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    17. // static final String DB_URL = "jdbc:mysql://10.129.18.17:3306/hfqx?useUnicode=true&characterEncoding=utf-8";
    18. //
    19. // // Database credentials
    20. // static final String USER = "root";
    21. // static final String PASS = "123";
    22. static final String DB_URL = JdbcUtil.getJDBCURL();
    23. static final String JDBC_DRIVER = JdbcUtil.getJDBCDriver();
    24. static final String USER = JdbcUtil.getUserName();
    25. static final String PASS = JdbcUtil.getPassWord();
    26. Connection conn = null;
    27. Statement stmt = null;
    28. {
    29. try
    30. {
    31. // Class.forName("com.mysql.jdbc.Driver");
    32. System.out.println(JDBC_DRIVER + " " + DB_URL + " "
    33. + USER + " " + PASS);
    34. Class.forName(JDBC_DRIVER);
    35. System.out.println("Connecting to database...");
    36. //STEP 3: Open a connection
    37. conn = DriverManager.getConnection(DB_URL, USER, PASS);
    38. //STEP 4: Execute a query
    39. System.out.println("Creating statement...");
    40. stmt = conn.createStatement();
    41. } catch(ClassNotFoundException e) {
    42. e.printStackTrace();
    43. } catch(SQLException e) {
    44. e.printStackTrace();
    45. }
    46. }
    47. @Override
    48. public ResultSet executesql(String sql) {
    49. ResultSet rs = null;
    50. try {
    51. rs = stmt.executeQuery(sql);
    52. } catch (SQLException e) {
    53. e.printStackTrace();
    54. }
    55. return rs;
    56. }
    57. @Override
    58. public List<String> queryForList(String sql) {
    59. ResultSet resultSet = executesql(sql);
    60. List<String> resultlist = new ArrayList<String>();
    61. try {
    62. while(resultSet.next()) {
    63. String stationid1 = resultSet.getString(1);
    64. resultlist.add(stationid1);
    65. }
    66. } catch (SQLException e) {
    67. e.printStackTrace();
    68. }
    69. return resultlist;
    70. }
    71. @Test
    72. public void TestSql() {
    73. DaoImp daoImp = new DaoImp();
    74. String sql = "SELECT Station_Id_C FROM STATION_META_TAB";
    75. List<String> resultlist = daoImp.queryForList(sql);
    76. System.out.println(resultlist.size());
    77. }
    78. }