帮我写个DBUtil模板
时间: 2023-06-01 17:02:24 浏览: 70
以下是一个基本的DBUtil模板,它使用Java的JDBC API连接到MySQL数据库,执行查询并返回结果集:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBUtil {
private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String DB_USERNAME = "myusername";
private static final String DB_PASSWORD = "mypassword";
public static Connection getConnection() throws SQLException {
Connection connection = null;
try {
// Load the JDBC driver
Class.forName(DB_DRIVER);
// Create the connection
connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return connection;
}
public static ResultSet executeQuery(String sql, Object... params) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
// Get the connection
connection = getConnection();
// Create the prepared statement
statement = connection.prepareStatement(sql);
// Set the parameters
for (int i = 0; i < params.length; i++) {
statement.setObject(i + 1, params[i]);
}
// Execute the query
resultSet = statement.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Close the resources
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
}
return resultSet;
}
}
在使用时,可以通过以下方式来执行查询:
ResultSet resultSet = DBUtil.executeQuery("SELECT * FROM mytable WHERE id = ?", 1);
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
// ...
}
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)