DBHelper类
Posted maoxiuying
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DBHelper类相关的知识,希望对你有一定的参考价值。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBHelper {
private static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static String url = "jdbc:sqlserver://localhost:1433;DatabaseName=SchoolDB";
private static String userName = "sa";
private static String pwd = "sa";
public static Connection getConnection(){
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection con = null;
try {
con = DriverManager.getConnection(url,userName,pwd);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
//执行动作查询:添加、修改、删除
public static int executeUpdate(String sql,Object ...obj) {
int n = 0;
Connection con = getConnection();
try {
PreparedStatement ps = con.prepareStatement(sql);
for (int i = 0; i < obj.length; i++) { //初始化参数
ps.setObject(i+1, obj[i]);
}
n = ps.executeUpdate(); //执行动作查询
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return n;
}
//执行动作查询:添加、修改、删除(封装)
public static ResultSet executeQuery(String sql, Object ...obj){
ResultSet set = null;
Connection con = getConnection();
try {
PreparedStatement ps = con.prepareStatement(sql);
for (int i = 0; i < obj.length; i++) {
ps.setObject(i+1, obj[i]);
}
set = ps.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return set;
}
}
以上是关于DBHelper类的主要内容,如果未能解决你的问题,请参考以下文章