web后台中用jdbc连接mysql

具体操作步骤如下:

    1. 新建java文件,写连接DB和关闭DB的方法;

    private String driverName = "com.mysql.jdbc.Driver";
    private String userName = "test";
    private String userPwd = "111111";
    private String dbName = "dbName";

    private String url = "jdbc:mysql://xxx/" + dbName + "?user="
        + userName + "&password=" + userPwd + "&characterEncoding=utf-8";
    //private String url = "jdbc:mysql://xxx/" + dbName + "?characterEncoding=utf-8";

    public Connection conn = null;
    public Statement sm = null;
    public void ConnectDB() {
        try {
            Class.forName(driverName).newInstance();
            conn = DriverManager.getConnection(url);
            //conn = DriverManager.getConnection(url, userName, userPwd);
            sm = conn.createStatement();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
     }

     public void CloseDB() {
         try {
             if (sm != null) {
                 sm.close();
             }
             conn.close();
         } catch (SQLException ex) {
             ex.printStackTrace();
         }
      }

    2. 在需要使用数据的地方;

  XXXDb db = new XXXDb();
  db.ConnectDB();
  Connection conn = db.conn;
  String sql = "xxxx";
  PreparedStatement pstmt = conn.prepareStatement(sql);
  ResultSet rs = pstmt.executeQuery();
  while(rs.next()) {
      String module = rs.getString("xxx");
      ......
  }

 

你可能感兴趣的:(数据库,mysql,web开发)