mysql dbutil怎么写

mysql dbutil怎么写,第1张

DbUtils类为做一些诸如关闭连接、装载JDBC驱动程序之类的常规工作提供有用方法的类,它里面所有的方法都是静态的。

A:loadDriver(StringdriveClassName): 这一方法装载并注册JDBC驱动程序,如果成功就返回TRUE,不需要去捕捉ClassNotFoundException异常。通过返回值判断驱动程序是否加载成功。

B:close方法:DbUtils类提供了三个重载的关闭方法。这些方法检查所提供的参数是不是NULL,如果不是的话,它们就关闭连接(Connection)、声明(Statement)或者结果集(ResultSet)对象。

C:closeQuietly方法: closeQuietly这一方法不仅能在连接、声明或者结果集为NULL情况下避免关闭,还能隐藏一些在程序中抛出的SQLException。如果你不想捕捉这些异常的话,这对你是非常有用的。在重载closeQuietly方法时,特别有用的一个方法是 closeQuietly(Connection conn,Statement stmt,ResultSet rs),使用这一方法,你最后的块就可以只需要调用这一方法即可。

D: commitAndCloseQuietly(Connection conn)方法和commitAndClose (Connection conn)方法:这两个方法用来提交连接,然后关闭连接,不同的是commitAndCloseQuietly(Connection conn)方法关闭连接时不向上抛出在关闭时发生的一些SQL异常而commitAndClose (Connection conn)方法向上抛出SQL异常。

1,首先写个方法package utilimport java.sql.Connection

import java.sql.DriverManager

import java.sql.SQLExceptionpublic class DBUtil { static String jdbcURL = "jdbc:mysql://localhost:3306/book"

static String jdbcDriver = "com.mysql.jdbc.Driver"

static String userName = "root"

static String password = "root"

/**

* 获取数据库连接对象

* @return 数据库连接对象

* @throws ClassNotFoundException

* @throws SQLException

*/

public static Connection getConnection() throws ClassNotFoundException,

SQLException {

Class.forName(jdbcDriver)

return DriverManager.getConnection(jdbcURL, userName, password)

}

} 2。项目名==>右键==>build path==>add external archivers.... 选择你mysql驱动 添加进去就ok了

private static void test3() throws Exception{

Connection con=null

PreparedStatement pstmt=null

ResultSet rs=null

try{

con=DBUtil.openInThread()

String sql="show tables"

pstmt=con.prepareStatement(sql)

rs= pstmt.executeQuery()

while(rs.next()){

System.out.println(rs.getString(1))

}

}finally{

DBUtil.close(null,pstmt, rs)

DBUtil.closeInThread()

}

} 我这样会输出表名


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/6094468.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-14
下一篇 2023-03-14

发表评论

登录后才能评论

评论列表(0条)

保存