您现在的位置是:首页 > 文章详情

Java数据库通用操作类的代码

日期:2021-04-25点击:545

        Java操作数据库主要有以下三个步骤:1)查找数据库驱动;2)生成Connection对象;3)生成Statement对象,然后使用Statement对象进行数据库的增删改查操作。为了更加方便使用,对上述操作进行封装,增删改三个操作封装为update方法,参数为标准的SQL语句,返回值为boolean类型;查询封装为query方法,方法的参数也为标准的查询SQL语句,返回为记录集ResultSet;单独编写initialize方法实现配置文件读取,Connection对象生成,Statement生成等操作,并将initialize()方法与类的构造函数合并,即一生成类对象即完成初始化操作;close()方法实现了对数据资源回收工作,值得注意的是在初始化操作时,是先生成Connection对象,再生成Statement对象,而关闭时是先关闭Statement对象再关闭Connection对象,这一点一定要注意。

        数据库类中可能发生变化的内容:数据库驱动,url,用户名和密码,单独在配置文件中,防止发生变化时需要修改和重新编译代码。

        配置文件内容如下:

driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8 username=root password=test

        具体DBProcess.java的代码如下:

package edu.sgit.db; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.Properties; /*  * 表名:test  * id       int 自增  * username varchar(50)  * password varchar(50)  *   */ //insert into test(username,password)  //                values('admin','111'); //update test set password='222' where id=1 //update test set password='222' where username='admin' //delete from test where id=1; // delete from test where username='admin' // select * from test where username='admin' public class DBProcess { private Connection conn = null; private Statement  stmt = null; public DBProcess(){ initialize(); } public void initialize(){ try{ String driver="";//数据库驱动类 String url=""; String username=""; String password=""; //读配置文件,获取,driver,url,username,password InputStream in = this.getClass().getResourceAsStream("prop.properties"); //字节流 Properties prop = new Properties();  try {    prop.load(in);  } catch (IOException e) {     e.printStackTrace();  }  driver = prop.getProperty("driver"); url=prop.getProperty("url"); username = prop.getProperty("username"); password = prop.getProperty("password"); //1.查找数据库驱动 Class.forName(driver);//查找数据库驱动 //2.建立数据库连接,并生成相应的连接对象 conn = DriverManager.getConnection(url,username,password);//建立数据库连接 //3.生成数据库操作对象stmt stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); }catch(Exception ex){ ex.printStackTrace(); } } //在数据表中添加,修改,删除一条记录 public boolean update(String sql){ try{ //添加 //insert into test(username,password)              //  values('admin','111'); //修改数据库记录 //update test set password='222222' where id=1, //删除记录 //sql = "delete from test where id=8" stmt.executeUpdate(sql); return true; }catch(Exception ex){ ex.printStackTrace(); return false; } } //查询结果 //sql ="select * from test" public ResultSet query(String sql){ try{ return stmt.executeQuery(sql); }catch(Exception ex){ ex.printStackTrace(); return null; } } public void close(){ try{ if(stmt!=null) stmt.close(); if(conn!=null) conn.close(); }catch(Exception ex){ ex.printStackTrace(); } } }


测试代码:

package edu.sgit.test; import java.sql.ResultSet; import edu.sgit.db.DBProcess; public class DBTest { public static void main(String[] args) { /* +--------+--------------+------+-----+---------+----------------+ | Field  | Type         | Null | Key | Default | Extra          | +--------+--------------+------+-----+---------+----------------+ | Id     | int(11)      | NO   | PRI | NULL    | auto_increment | | title  | varchar(100) | YES  |     | NULL    |                | | msg    | text         | YES  |     | NULL    |                | | inDate | datetime     | YES  |     | NULL    |                | | count  | int(11)      | YES  |     | 0       |                | +--------+--------------+------+-----+---------+----------------+  * */ DBProcess db = new DBProcess(); //add String title="abc"; String msg="msg_0001"; String date="2020-09-20 10:45:23"; int count=100; int id=8; //如果字段是字符,变量前后加'',如果字段是数值类型,不加单引号 //title:'aaa0000' //count:100 String sql0="insert into msg(title,msg,inDate,count) values('abc','msg_0001','2020-09-20 10:45:23',100)"; String sql1="insert into msg(title,msg,inDate,count) values('"; sql1 = sql1 + title +"','"; sql1 = sql1 + msg +"','"; sql1 = sql1 + date +"',"; sql1 = sql1 + count +")"; System.out.println(sql1); boolean flag = db.update(sql1); if(flag) { System.out.println("add ok!"); }else { System.out.println("add error!"); } //update sql1 ="update msg set title='"; sql1 = sql1+title+"' where id="+id; flag = db.update(sql1); if(flag) { System.out.println("udpate ok!"); }else { System.out.println("udpate error!"); } //delete sql1 ="delete from msg where id="+id; flag = db.update(sql1); if(flag) { System.out.println("delete ok!"); }else { System.out.println("delete error!"); } //query sql1 ="select * from msg"; ResultSet rs = db.query(sql1); try { while(rs.next()) { System.out.print(rs.getInt("id")); System.out.print("\t"); System.out.print(rs.getString("title")); System.out.print("\t"); System.out.print(rs.getString("msg")); System.out.print("\t"); System.out.print(rs.getString("inDate")); System.out.print("\t"); //System.out.print(rs.getInt("count")); //System.out.print("\n"); } }catch(Exception ex) { ex.printStackTrace(); } } }
原文链接:https://blog.51cto.com/u_2768919/2731566
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章