Java SQL Server 工具类 - 连接、查询和关闭数据库
以下是一个示例的 Java SQL Server 工具类:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SQLServerUtils {
private static final String DRIVER_CLASS = 'com.microsoft.sqlserver.jdbc.SQLServerDriver';
private static final String CONNECTION_URL = 'jdbc:sqlserver://localhost:1433;databaseName=your_database_name';
private static final String USERNAME = 'your_username';
private static final String PASSWORD = 'your_password';
public static Connection getConnection() {
try {
Class.forName(DRIVER_CLASS);
return DriverManager.getConnection(CONNECTION_URL, USERNAME, PASSWORD);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return null;
}
public static void closeConnection(Connection connection) {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void closeStatement(Statement statement) {
try {
if (statement != null) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void closeResultSet(ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
使用示例:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Main {
public static void main(String[] args) {
Connection connection = SQLServerUtils.getConnection();
if (connection != null) {
try {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery('SELECT * FROM your_table_name');
while (resultSet.next()) {
// 处理结果集
int id = resultSet.getInt('id');
String name = resultSet.getString('name');
System.out.println('id: ' + id + ', name: ' + name);
}
SQLServerUtils.closeResultSet(resultSet);
SQLServerUtils.closeStatement(statement);
} catch (SQLException e) {
e.printStackTrace();
} finally {
SQLServerUtils.closeConnection(connection);
}
}
}
}
你需要将your_database_name替换为你的数据库名称,your_username替换为你的数据库用户名,your_password替换为你的数据库密码,your_table_name替换为你要查询的表名。
原文地址: https://www.cveoy.top/t/topic/dpI4 著作权归作者所有。请勿转载和采集!