Java当中数据库访问类:DB类

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

DB类是项目用来连接数据库的辅助类:

封装和数据库的连接。

主要是和数据库连接的相关信息:

1.找到驱动程序

Class.forName("com.mysql.jdbc.Driver");

2.连接字符串

DriverManager.getConnection("jdbc:mysql://localhost/shopping?user=roo t&password=root");

3.PreparedStatement

4.Statement

5. Result

package com.bjsxt.shopping.util;

import java.sql.*;

publicclass DB {

publicstatic Connection getConn() {

Connection conn = null;

try {

Class.forName("com.mysql.jdbc.Driver");

conn =

DriverManager.getConnection("jdbc:mysql://localhost/shopping?user=roo t&password=root");

} catch (ClassNotFoundException e) {

e.printStackTrace();

} catch (SQLException e) {

e.printStackTrace();

}

return conn;

}

publicstatic PreparedStatement prepare(Connection conn, String sql) {

PreparedStatementpstmt = null;

try {

if(conn != null) {

pstmt = conn.prepareStatement(sql);

}

} catch (SQLException e) {

e.printStackTrace();

}

return pstmt;

}

publicstatic PreparedStatement prepare(Connection conn, String sql, int autoGenereatedKeys) {

PreparedStatementpstmt = null;

try {

if(conn != null) {

pstmt = conn.prepareStatement(sql, autoGenereatedKeys);

}

} catch (SQLException e) {

e.printStackTrace();

}

return pstmt;

}

publicstatic Statement getStatement(Connection conn) {

Statement stmt = null;

try {

if(conn != null) {

stmt = conn.createStatement();

}

} catch (SQLException e) {

e.printStackTrace();

}

return stmt;

}

/*

public static ResultSetgetResultSet(Connection conn, String sql) { Statement stmt = getStatement(conn);

ResultSetrs = getResultSet(stmt, sql);

close(stmt);

returnrs;

}

*/

publicstatic ResultSetgetResultSet(Statement stmt, String sql) { ResultSetrs = null;

try {

if(stmt != null) {

rs = stmt.executeQuery(sql);

}

} catch (SQLException e) {

e.printStackTrace();

}

return rs;

}

publicstaticvoid executeUpdate(Statement stmt, String sql) { try {

if(stmt != null) {

stmt.executeUpdate(sql);

}

} catch (SQLException e) {

e.printStackTrace();

}

}

publicstaticvoid close(Connection conn) {

try {

if(conn != null) {

conn.close();

conn = null;

}

} catch (SQLException e) {

e.printStackTrace();

}

}

publicstaticvoid close(Statement stmt) {

try {

if(stmt != null) {

stmt.close();

stmt = null;

}

} catch (SQLException e) {

e.printStackTrace();

}

}

publicstaticvoid close(ResultSetrs) {

try {

if(rs != null) {

rs.close();

相关文档
最新文档