java web資料庫操作
阿新 • • 發佈:2019-02-15
這是自己初期學習java mvc模式時整理的jdbc連線資料庫的程式碼,資料庫為mysql
ConnDB是基礎類,封裝了連線資料庫需要的一些資訊。
package com.hsp.model; import java.sql.*; public class ConnDB { private Connection ct=null; public Connection getConn(){ try{ Class.forName("com.mysql.jdbc.Driver"); ct=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root","czcat"); }catch(Exception ex){ ex.printStackTrace(); } return ct; } }
增加操作
public boolean addUser(String username,String password,int date,int grade){ boolean b=false; try { ct=new ConnDB().getConn(); sm=ct.createStatement(); int a=sm.executeUpdate("insert into xs(username,password,date,grade) values('"+username+"','"+password+"','"+date+"','"+grade+"')"); if(a==1){ b=true; } } catch (Exception e) { e.printStackTrace(); }finally{ this.close(); } return b; }
刪改操作
public boolean delUserById(String id){ boolean b=false; try { ct=new ConnDB().getConn(); sm=ct.createStatement(); int a=sm.executeUpdate("delete from xs where userid='"+id+"'"); if(a==1){ b=true; } } catch (Exception e) { e.printStackTrace(); }finally{ this.close(); } return b; }
修改操作
public boolea update(int userid,String username,String password,int date,int grade){
boolean b=false;
try {
ct=new ConnDB().getConn();
sm=ct.createStatement();
int a=sm.executeUpdate("update xs SET username='"+username+"',password='"+password+"',date='"+date+"',grade='"+grade+"' where userid='"+userid+"'");
if(a==1){
b=true;
}
} catch (Exception e) {
e.printStackTrace();
}finally{
this.close();
}
return b;
}
查詢操作
public boolean checkUser(String u,String p){
boolean b=false;
try {
ct=new ConnDB().getConn();
sm=ct.createStatement();
rs=sm.executeQuery("select password from xs where username='"+u
+"'");
if(rs.next())
{
if(rs.getString(1).equals(p)){
b=true;
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
this.close();
}
return b;
}
}
關閉流
public void close(){
try {
if(rs!=null){
rs.close();
rs=null;
}
if(sm!=null){
sm.close();
sm=null;
}
if(ct!=null){
ct.close();
ct=null;
}
} catch (Exception e2) {
e2.printStackTrace();
}
}