欢迎来到天天文库
浏览记录
ID:62037255
大小:18.13 KB
页数:4页
时间:2021-04-15
《Java当中数据库访问类:DB类.docx》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、DB类是项目用来连接数据库的辅助类:封装和数据库的连接。主要是和数据库连接的相关信息:1.找到驱动程序Class.forName("com.mysql.jdbc.Driver");2.连接字符串DriverManager.getConnection("jdbc:mysql://localhost/shopping?user=root&password=root");3.PreparedStatement4.Statement5.Resultpackagecom.bjsxt.shopping.util;importjava.sql.*;publiccl
2、assDB{publicstaticConnectiongetConn(){Connectionconn=null;try{Class.forName("com.mysql.jdbc.Driver");conn=DriverManager.getConnection("jdbc:mysql://localhost/shopping?user=root&password=root");}catch(ClassNotFoundExceptione){e.printStackTrace();}catch(SQLExceptione){e.printStac
3、kTrace();}returnconn;}publicstaticPreparedStatementprepare(Connectionconn,Stringsql){PreparedStatementpstmt=null;try{if(conn!=null){pstmt=conn.prepareStatement(sql);}}catch(SQLExceptione){e.printStackTrace();}returnpstmt;}publicstaticPreparedStatementprepare(Connectionconn,Stri
4、ngsql,intautoGenereatedKeys){PreparedStatementpstmt=null;try{if(conn!=null){pstmt=conn.prepareStatement(sql,autoGenereatedKeys);}}catch(SQLExceptione){e.printStackTrace();}returnpstmt;}publicstaticStatementgetStatement(Connectionconn){Statementstmt=null;try{if(conn!=null){stmt=
5、conn.createStatement();}}catch(SQLExceptione){e.printStackTrace();}returnstmt;}/*publicstaticResultSetgetResultSet(Connectionconn,Stringsql){Statementstmt=getStatement(conn);ResultSetrs=getResultSet(stmt,sql);close(stmt);returnrs;}*/publicstaticResultSetgetResultSet(Statementst
6、mt,Stringsql){ResultSetrs=null;try{if(stmt!=null){rs=stmt.executeQuery(sql);}}catch(SQLExceptione){e.printStackTrace();}returnrs;}publicstaticvoidexecuteUpdate(Statementstmt,Stringsql){try{if(stmt!=null){stmt.executeUpdate(sql);}}catch(SQLExceptione){e.printStackTrace();}}publi
7、cstaticvoidclose(Connectionconn){try{if(conn!=null){conn.close();conn=null;}}catch(SQLExceptione){e.printStackTrace();}}publicstaticvoidclose(Statementstmt){try{if(stmt!=null){stmt.close();stmt=null;}}catch(SQLExceptione){e.printStackTrace();}}publicstaticvoidclose(ResultSetrs)
8、{try{if(rs!=null){rs.close();rs=null;}}catch(SQLExcept
此文档下载收益归作者所有