第一步:构建操作数据库的类
package com.sc.test3;
import java.sql.*;
/**
* 这是操作数据的类
* @author ZhangShaoWen
*
*/
public class SqlHelper {
//定义操作数据库的一些变量
Connection conn = null;
ResultSet rs = null;
PreparedStatement ps = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String url = "jdbc:sqlserver://localhost:1433;databaseName=Test";
String user = "sa";
String passw = "100862";
//连接数据库
public void linkSql(){
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,user,passw);
} catch (Exception e) {
e.printStackTrace();
}
}
//关闭数据库资源
public void closeSql(){
try {
if(rs!=null) rs.close();
if(ps!=null) ps.close();
if(conn!=null) conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//对表的增、删、改操作
public boolean updExecute(String sql,String[] paras){
boolean b = true;
//连接数据库
this.linkSql();
try {
//初始化ps
ps = conn.prepareStatement(sql);
//给?赋值
for(int i=0;i<paras.length;i++){
ps.setString(i+1, paras[i]);
}
//执行executeUpdate操作
if(ps.executeUpdate()!=1){
b = false;
}
} catch (Exception e) {
b = false;
e.printStackTrace();
}finally{
//关闭资源
this.closeSql();
}
return b;
}
//对表的查询操作,含注入参数
public ResultSet queryExecute(String sql,String[] paras){
//连接数据库
this.linkSql();
try {
//创建ps
ps = conn.prepareStatement(sql);
//给?赋值
for(int i=0;i<paras.length;i++){
ps.setString(i+1, paras[i]);
}
//执行操作
rs = ps.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}finally{
//数据库资源到model中去关闭
}
return rs;
}
//对表的查询操作,不含注入参数
public ResultSet queryExecute(String sql){
//连接数据库
this.linkSql();
try {
//创建ps
ps = conn.prepareStatement(sql);
//执行操作
rs = ps.executeQuery(sql);
} catch (Exception e) {
e.printStackTrace();
}finally{
//数据库资源到model中去关闭
}
return rs;
}
}