java web数据库操作

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值