public class DBUtil {
/**
* @param args
*/
static {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConn(){
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;datebaesName=MyDB", "sa", "1");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public static void close(Connection conn,PreparedStatement ps,ResultSet rs){
try {
if(conn!=null)
conn.close();
if(ps!=null)
ps.close();
if(rs!=null)
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static int update(String sql,Object[] objs){
Connection conn = getConn();
PreparedStatement ps = null;
int count = 0;
try {
ps = conn.prepareStatement(sql);
for(int i = 0; i < objs.length; i++){
ps.setObject(i+1, objs[i]);
}
count = ps.executeUpdate();
if(count>0){
System.out.println("成功");
}else{
System.out.println("失败");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
close(conn, ps, null);
}
return count;
}
}
public static void main(String[] args) {
String sql = "update student set pwd = ? and id = ?";
Object[] objs = {"1234",2};
int count = DBUtil.update(sql, objs);
if(count > 0){
System.out.println("修改成功");
}else{
System.out.println("修改成功");
}
String sql2 = "insert into student (user_name,pwd,age,sex) valuse (?,?,?,?) ";
Object[] objs2 = {"xiaoming","123456",20,"男"};
int count2 = DBUtil.update(sql, objs);
if(count > 0){
System.out.println("新增成功");
}else{
System.out.println("新增失败");
}
String sql3 = "delect from student where id = ? ";
Object[] objs3 = {20};
int count3 = DBUtil.update(sql, objs);
if(count > 0){
System.out.println("" +
"删除成功");
}else{
System.out.println("删除失败");
}
}
public static User login(Integer id) {
Connection conn = DBUtil.getConn();
String sql = "select * from student where id = ?";
PreparedStatement ps = null;
ResultSet rs = null;
User user = null;
try {
ps = conn.prepareStatement(sql);
ps.setInt(1,id);
rs = ps.executeQuery();
if(rs.next()){
user = new User();
user.setId(rs.getInt(1));
user.setUser_name(rs.getString(2));
user.setPwd(rs.getString(3));
user.setAge(rs.getInt(4));
user.setSex(rs.getString(5));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBUtil.close(conn, ps, rs);
}
return user;