SQL Server 数据库连接类

时间:2022-10-08 00:42:30
package edu.qdgxy.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

//1.加载驱动;2.建立连接3.创建Statement对象4.执行sql 5.关闭资源
public class DBBean {

private String driverStr = "com.microsoft.sqlserver.jdbc.SQLServerDriver";

private String connStr = "jdbc:sqlserver://localhost:1433;databaseName=PEM";
//jdbc:sqlserver://localhost:1433;databaseName=数据库的名字
private String username="sa";
private String password="sa";
private Connection connection = null;
private Statement stmt=null;
private ResultSet rs = null;

public DBBean() {
try {
Class.forName(driverStr);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

private Connection getConnection(){
try {
connection=DriverManager.getConnection(connStr,username,password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}

private Statement createStatement(){
try {
stmt=getConnection().createStatement();
} catch (Exception e) {
e.printStackTrace();
}
return stmt;
}
public ResultSet executeQuery(String sql) {
try {
rs = createStatement().executeQuery(sql);
} catch (Exception e) {
e.printStackTrace();
}
return rs;
}

public int executeUpdate(String sql) {
int result = 0;
try {
result = createStatement().executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}

public void close(){
try {
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

}