sqlHelp的记录
package balance.sql;
import java.io.*;
import java.sql.*;
import java.util.*;
public class sqlHelper {
private Connection ct=null;
private static PreparedStatement ps=null;
private static ResultSet rs=null;
private static String driver=null;
private static String url=null;
private static String username=null;
private static String password=null;
private static Properties pp=null;
private static FileInputStream fis=null;
//驱动只需加载一次
static{
try{
pp = new Properties();
fis = new FileInputStream("dbinfo.properties");
pp.load(fis);
driver = pp.getProperty("driver");
url = pp.getProperty("url");
username = pp.getProperty("username");
password = pp.getProperty("password");
Class.forName(driver);
}catch(Exception e){
e.printStackTrace();
}finally{
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
fis=null;
}
}
//连接
public Connection getConnection(){
try {
ct = DriverManager.getConnection(url,username,password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ct;
}
//查询
public ResultSet executeQuery(String sql,String []parameters){
try {
ct = getConnection();
ps = ct.prepareStatement(sql);
for(int i=0;i<parameters.length;i++){
ps.setObject(i+1, parameters[i]);
}
rs = ps.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}
return rs;
}
//单个dml语句
public void executeUpdate(String sql,String []parameters){
try{
ct = getConnection();
ps = ct.prepareStatement(sql);
if(parameters!=null){
for(int i=0;i<parameters.length;i++){
ps.setObject(i+1, parameters[i]);
}
}
ps.executeUpdate();
}catch(Exception e){
e.printStackTrace();
//抛出运行异常
//throw new RuntimeException(e.getMessage());
}finally{
this.close(rs, ps, ct);
}
}
//如果有多个update/delete/insert
public void executeUpdate2(String sql[],String [][]parameters){
try{
//获取连接
ct = getConnection();
ct.setAutoCommit(false);
for(int i=0;i<sql.length;i++){
if(parameters[i]!=null){
ps=ct.prepareStatement(sql[i]);
for(int j=0;j<parameters[i].length;j++){
ps.setObject(j+1, parameters[i][j]);
}
ps.executeUpdate();
}
}
ct.commit();
}catch(Exception e){
e.printStackTrace();
try {
ct.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//抛出运行异常
throw new RuntimeException(e.getMessage());
}finally{
this.close(rs, ps, ct);
}
}
public void close(ResultSet rs,Statement ps,Connection ct){
if(rs!=null){
try{
rs.close();
}catch(Exception e){
e.printStackTrace();
}
rs=null;
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
ps=null;
}
if(ct!=null){
try {
ct.close();
} catch (SQLException e) {
e.printStackTrace();
}
ct=null;
}
}
}
driver、url、password、username都设置在properties属性配置文件里

浙公网安备 33010602011771号