码迷,mamicode.com
首页 > 数据库 > 详细

DBHelper类

时间:2018-05-16 12:56:10      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:res   初始   red   添加   get   basename   host   except   use   

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类

标签:res   初始   red   添加   get   basename   host   except   use   

原文地址:https://www.cnblogs.com/maoxiuying/p/9044891.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!