最简谱的jdbc程序

来源:互联网 发布:c语言编程软件官方下载 编辑:程序博客网 时间:2024/04/24 19:37

1

import java.sql.*;  import java.util.ResourceBundle;  public class DBUtil {      private static Connection conn = null;      private static Statement stmt;      private static PreparedStatement pstmt = null;      private static String url = "", driver = "", userName = "", password = "";      static {          ResourceBundle bundle = ResourceBundle.getBundle("jdbc");          url = bundle.getString("jdbc.url");          driver = bundle.getString("jdbc.driverClassName");          userName = bundle.getString("jdbc.username");          password = bundle.getString("jdbc.password");      }      public DBUtil() {      }      public static Connection getConnection() {          try {              Class.forName(driver);              conn = DriverManager.getConnection(url, userName, password);          } catch (Exception e) {              e.printStackTrace();          }          return conn;      }  }  

2

    package jdbc;      import java.sql.*;      import jdbc.model.User;      import jdbc.util.DBUtil;      public class JDBCDemo {          public static User getUser(int id) throws SQLException {              User user = null;              String sql = "select * from users where ID=?";              Connection conn = null;              PreparedStatement pstmt = null;              ResultSet rs = null;              try {                  conn = DBUtil.getConnection();                  pstmt = conn.prepareStatement(sql);                  pstmt.setInt(1, id);                  rs = pstmt.executeQuery();                  while (rs.next()) {                      user = new User();                      user.setUserId(rs.getInt("ID"));                      user.setUserName(rs.getString("USERNAME"));                      user.setPassword(rs.getString("PASSWORD"));                      user.setMobile(rs.getString("MOBILE"));                      user.setEmail(rs.getString("EMAIL"));                  }              } finally {                  try {                      if (rs != null) {                          rs.close();                      }                  } finally {                      try {                          if (pstmt != null) {                              pstmt.close();                          }                      } finally {                          if (conn != null) {                              conn.close();                          }                      }                  }              }              return user;          }          public static void main(String[] args) throws Exception {              System.out.println(getUser(1));          }      }  


3jdbc.properties

    jdbc.driverClassName=com.mysql.jdbc.Driver      jdbc.url=jdbc:mysql://localhost:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=utf8      jdbc.username=root      jdbc.password=123  



0 0