* 连接数据库并获取数据库中的数据的类:GetConnectionDB
*/
public class CocnnectionDB {
Connection conn = null; // 创建连接对象conn
PreparedStatement pst = null; // 创建预编译对象pst
ResultSet rs = null; // 创建结果集对象rs
String className = "com.microsoft.sqlserver.jdbc.SQLServerDriver";// 驱动程序包的途径
String url = "jdbc:sqlserver://localhost:1433;databaseName=dengli"; // 驱动程序路径
String user = "sa";// 数据库用户名sa
String pw = "wwy000111";// 数据库密码
/**
* 类GetConnectionDB的构造方法
*/
public CocnnectionDB() {
try {
Class.forName(className); // 驱动程序方法;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 下面是连接数据库的getConn()方法并返回Connection对象
*/
private Connection getConn() {
try {
conn = DriverManager.getConnection(url, user, pw); // 使用驱动器连接数据库
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* 下面是各对象的关闭方法
*/
public void closeAll(ResultSet rs, PreparedStatement pst, Connection conn) {
try {
if (rs != null) {
rs.close();
}
if (pst != null) {
pst.close(); // 判断各对象是否为空并进行不为空的关闭
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 下面执行sql语句并返回结果集对象rs(主要针对sql的查询语句)
*/
public ResultSet returnSet(String sql) {
try {
conn = this.getConn();
pst = conn.prepareStatement(sql);
rs = pst.executeQuery(); // 执行sql并返回结果集rs
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rs;
}
/**
* 下面执行sql语句并返回受影响的行数(主要针对sql的添加语句,修改语句以及删除语句)
*/
private int count = 0; // 定义一个受影响的行数count并初始化为0
public int dealSql(String sql) {
try {
conn = this.getConn();
pst = conn.prepareStatement(sql);
count = pst.executeUpdate(); // 对sql语句进行增删改并放回受影响的行数count
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
this.closeAll(rs, pst, conn); // 执行完成后关闭各个对象
}
return count;
}
//
//public static void main(String[] args) {
//// TODO Auto-generated method stub
//GetConnectionDB a=new GetConnectionDB();
//System.out.println(a.getConn());
//}
//
}