抽取JDBC工具类
以下是一个简单的JDBC工具类的示例:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCUtils {
private static final String URL = "jdbc:mysql://localhost:3306/database_name";
private static final String USERNAME = "username";
private static final String PASSWORD = "password";
public static Connection getConnection() {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void closeConnection(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
使用该工具类,您可以获取数据库连接和关闭连接。示例如下:
Connection connection = JDBCUtils.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM table_name");
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
// 处理结果集
}
JDBCUtils.closeConnection(connection, preparedStatement, resultSet);
请注意,您需要将URL,USERNAME和PASSWORD替换为您自己的数据库连接信息
原文地址: http://www.cveoy.top/t/topic/h15w 著作权归作者所有。请勿转载和采集!