Java数据库通用操作类的代码
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的代码如下: packageedu.sgit.db; importjava.io.IOException; importjava.io.InputStream; importjava.sql.Connection; importjava.sql.DriverManager; importjava.sql.ResultSet; importjava.sql.Statement; importjava.util.Properties; /* *表名:test *idint自增 *usernamevarchar(50) *passwordvarchar(50) * */ //insertintotest(username,password) // values('admin','111'); //updatetestsetpassword='222'whereid=1 //updatetestsetpassword='222'whereusername='admin' //deletefromtestwhereid=1; //deletefromtestwhereusername='admin' //select*fromtestwhereusername='admin' publicclassDBProcess{ privateConnectionconn=null; privateStatementstmt=null; publicDBProcess(){ initialize(); } publicvoidinitialize(){ try{ Stringdriver="";//数据库驱动类 Stringurl=""; Stringusername=""; Stringpassword=""; //读配置文件,获取,driver,url,username,password InputStreamin=this.getClass().getResourceAsStream("prop.properties");//字节流 Propertiesprop=newProperties(); try{ prop.load(in); }catch(IOExceptione){ 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(Exceptionex){ ex.printStackTrace(); } } //在数据表中添加,修改,删除一条记录 publicbooleanupdate(Stringsql){ try{ //添加 //insertintotest(username,password) //values('admin','111'); //修改数据库记录 //updatetestsetpassword='222222'whereid=1, //删除记录 //sql="deletefromtestwhereid=8" stmt.executeUpdate(sql); returntrue; }catch(Exceptionex){ ex.printStackTrace(); returnfalse; } } //查询结果 //sql="select*fromtest" publicResultSetquery(Stringsql){ try{ returnstmt.executeQuery(sql); }catch(Exceptionex){ ex.printStackTrace(); returnnull; } } publicvoidclose(){ try{ if(stmt!=null) stmt.close(); if(conn!=null) conn.close(); }catch(Exceptionex){ ex.printStackTrace(); } } } 测试代码: packageedu.sgit.test; importjava.sql.ResultSet; importedu.sgit.db.DBProcess; publicclassDBTest{ publicstaticvoidmain(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|| +--------+--------------+------+-----+---------+----------------+ **/ DBProcessdb=newDBProcess(); //add Stringtitle="abc"; Stringmsg="msg_0001"; Stringdate="2020-09-2010:45:23"; intcount=100; intid=8; //如果字段是字符,变量前后加'',如果字段是数值类型,不加单引号 //title:'aaa0000' //count:100 Stringsql0="insertintomsg(title,msg,inDate,count)values('abc','msg_0001','2020-09-2010:45:23',100)"; Stringsql1="insertintomsg(title,msg,inDate,count)values('"; sql1=sql1+title+"','"; sql1=sql1+msg+"','"; sql1=sql1+date+"',"; sql1=sql1+count+")"; System.out.println(sql1); booleanflag=db.update(sql1); if(flag){ System.out.println("addok!"); }else{ System.out.println("adderror!"); } //update sql1="updatemsgsettitle='"; sql1=sql1+title+"'whereid="+id; flag=db.update(sql1); if(flag){ System.out.println("udpateok!"); }else{ System.out.println("udpateerror!"); } //delete sql1="deletefrommsgwhereid="+id; flag=db.update(sql1); if(flag){ System.out.println("deleteok!"); }else{ System.out.println("deleteerror!"); } //query sql1="select*frommsg"; ResultSetrs=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(Exceptionex){ ex.printStackTrace(); } } }