帮我写一个jdbc工具类,我的数据库是mysql
时间: 2023-05-25 21:05:48 浏览: 127
以下是一个简单的 JDBC 工具类,支持 MySQL 数据库连接:
```
import java.sql.*;
public class JdbcUtils {
/**
* 获取 MySQL 数据库连接
*
* @return Connection
*/
public static Connection getConnection() {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/test?useSSL=false";
String user = "root";
String password = "root";
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* 关闭数据库连接
*
* @param conn
* @param stmt
* @param rs
*/
public static void close(Connection conn, Statement stmt, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
使用方法示例:
```
public class Test {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
// 获取数据库连接
conn = JdbcUtils.getConnection();
// 执行查询
String sql = "SELECT * FROM student";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
JdbcUtils.close(conn, pstmt, rs);
}
}
}
```
阅读全文