这是自己初期学习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();
}
}