jdbc实现连接和增删改查功能
JDBC的定义
JDBC(JavaDataBaseConnectivity,java数据库连接)是一种用于执行SQL语句的JavaAPI,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。
jdbc的基本连接
简单的说就是加载驱动,建立连接,然后进行查询和删除等语句的操作,在java中提供了java.sql的jar包,不过我现在用的是mysql的连接和实例,在这里基本在本地的服务器都是用到下面这个语句。
Class.forName("com.mysql.jdbc.Driver"); Stringurl="jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf-8"; Stringuser="root"; Stringpassword="root";
加载和建立连接,这就是基本的一个语法结构,在连接数据库当然还有其他的属性可以设置,比如说最大的连接数了,和如何建立连接池,都可以在配置中用到,这里我就简单的介绍如何连接,后面跟的是这个连接的字符集,防止出现乱码。
简单的增删改查
简单的增删改查是每个开发者都会遇到的,毕竟我们整个系统真正的业务所在也是这几个简单的逻辑,但是在关系的连接和耦合性下就会变成复杂百倍的系统,所以要懂得基本的就可以窥见更大系统的构建了,所以我现在要分析的只是基本的功能实现。
首先连接好数据库之后,那就是创建查询语句,这里用到的是statment这个关键词,下面是代码的基本实现。
packagedbtest; importjava.sql.Connection; importjava.sql.DriverManager; importjava.sql.ResultSet; importjava.sql.SQLException; importjava.sql.Statement; importjava.text.SimpleDateFormat; importjava.util.ArrayList; importjava.util.Date; importjava.util.List; publicclassDbTest{ publicstaticvoidmain(String[]args){ Employeeemployee1=newEmployee(); employee1.setEmpno(555); employee1.setEname("hakly"); employee1.setSal(5400); employee1.setHiredate(newDate()); addEmployee(employee1); Listemployees=getEmployees(); for(Employeeemployee:employees){ System.out.println(employee); } Employeeemployee=newEmployee(); employee.setEmpno(999); employee.setEname("jack"); employee.setSal(5000); employee.setHiredate(newDate()); addEmployee(employee); } publicstaticList getEmployees(){ ResultSetrs=null; Connectionconn=null; Statementstat=null; List employees=newArrayList (); try{ Class.forName("com.mysql.jdbc.Driver"); Stringurl="jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf-8"; Stringuser="root"; Stringpassword="root"; conn=DriverManager.getConnection(url,user,password); stat=conn.createStatement(); Stringsql="select*fromemp"; rs=stat.executeQuery(sql); Employeeemployee=null; while(rs.next()){ employee=newEmployee(); employee.setEmpno(rs.getInt("empno")); employee.setEname(rs.getString("ename")); employee.setSal(rs.getDouble("sal")); employee.setHiredate(rs.getDate("hiredate")); employees.add(employee); } }catch(Exceptione){ e.printStackTrace(); }finally{ try{ if(conn!=null){ conn.close(); } }catch(SQLExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } } returnemployees; } publicstaticvoidaddEmployee(Employeeemployee){ Connectionconn=null; Statementstat=null; //1.注册驱动程序 try{ Class.forName("com.mysql.jdbc.Driver"); //2.建立连接 Stringurl="jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf-8"; Stringuser="root"; Stringpassword="root"; conn=DriverManager.getConnection(url,user,password); //3.创建执行语句,发送sql命令 stat=conn.createStatement(); SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-dd"); Stringsql="insertintoemp(empno,ename,sal,hiredate)values("+employee.getEmpno()+",'" +employee.getEname()+"',"+employee.getSal()+",'"+sdf.format(employee.getHiredate())+"')"; //4.处理执行结果 inti=stat.executeUpdate(sql); }catch(Exceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); }finally{ //5.关闭资源 try{ if(conn!=null){ conn.close(); } }catch(SQLExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } } } publicstaticvoidupdateEmployee(Employeeemployee){ Connectionconn=null; Statementstat=null; //1.注册驱动程序 try{ Class.forName("com.mysql.jdbc.Driver"); //2.建立连接 Stringurl="jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf-8"; Stringuser="root"; Stringpassword="root"; conn=DriverManager.getConnection(url,user,password); //3.创建执行语句,发送sql命令 stat=conn.createStatement(); SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-dd"); Stringsql="updateempsetename='"+employee.getEname()+"empno"+employee.getEmpno()+"sal"+employee.getSal(); //4.处理执行结果 inti=stat.executeUpdate(sql); }catch(Exceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); }finally{ //5.关闭资源 try{ if(conn!=null){ conn.close(); } }catch(SQLExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } } } }
这里的代码很繁琐,但是没办法,为了更清新一点的去了解,这个过程是必须的,然后接下来就是进行简单的优化,虽然代码还是差不多,但是感觉上会更加简洁了,这里就要建立一个工具类了代码如下
packagedbtest; importjava.sql.Connection; importjava.sql.DriverManager; importjava.sql.SQLException; publicclassJdbcUtil{ staticStringurl="jdbc:mysql://localhost:3306/xxx?useUnicode=true&characterEncoding=utf-8"; staticStringuser="root"; staticStringpassword="root"; static{ try{ Class.forName("com.mysql.jdbc.Driver"); }catch(ClassNotFoundExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } } publicstaticConnectiongetConnection()throwsSQLException{ Stringurl="jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf-8"; Stringuser="root"; Stringpassword="root"; returnDriverManager.getConnection(url,user,password); } publicstaticvoidfree(Connectionconn){ try{ if(conn!=null){ conn.close(); } }catch(SQLExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } } }
在这里,把数据库连接和异常处理,等工作都及合成一个工具类,然后再主函数调用就可以了,这就是面向对象的一个体现,当然还是会分析下关于主类的代码,要不然就太过于空洞了,下面要分析的主类代码如下
packagecom.niit.jdbc; importjava.sql.Connection; importjava.sql.DriverManager; importjava.sql.ResultSet; importjava.sql.SQLException; importjava.sql.Statement; importjava.text.ParseException; importjava.text.SimpleDateFormat; importjava.util.ArrayList; importjava.util.Date; importjava.util.List; publicclassEmployeeDao1{ publicstaticvoidmain(String[]args)throwsParseException{ Listemployees=getEmployees(); for(Employeeemployee:employees){ System.out.println(employee); } /*Employeeemployee=newEmployee(); employee.setEmpno(9999); employee.setEname("tom"); employee.setSal(6000); SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-dd"); employee.setHiredate(sdf.parse("2015-07-23")); //addEmployee(employee); //updateEmployee(employee); deleteEmployee(9999);*/ } publicstaticList getEmployees(){ Connectionconn=null; Statementstat=null; ResultSetrs=null; List employees=newArrayList (); //1.注册驱动程序 try{ //2.获取连接 conn=JdbcUtil.getConnection(); //3.创建执行语句,发送sql命令 stat=conn.createStatement(); Stringsql="select*fromemp"; //4.处理执行结果 rs=stat.executeQuery(sql); Employeeemployee=null; while(rs.next()){ employee=newEmployee(); employee.setEmpno(rs.getInt("empno")); employee.setEname(rs.getString("ename")); employee.setSal(rs.getDouble("sal")); employee.setHiredate(rs.getDate("hiredate")); employees.add(employee); } }catch(Exceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); }finally{ //5.关闭资源 JdbcUtil.free(conn); } returnemployees; } publicstaticvoidaddEmployee(Employeeemployee){ Connectionconn=null; Statementstat=null; //1.注册驱动程序 try{ //2.获取连接 conn=JdbcUtil.getConnection(); //3.创建执行语句,发送sql命令 stat=conn.createStatement(); SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-dd"); Stringsql="insertintoemp(empno,ename,sal,hiredate)values("+employee.getEmpno()+",'" +employee.getEname()+"',"+employee.getSal()+",'"+sdf.format(employee.getHiredate())+"')"; //4.处理执行结果 inti=stat.executeUpdate(sql); }catch(Exceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); }finally{ //5.关闭资源 JdbcUtil.free(conn); } } publicstaticvoidupdateEmployee(Employeeemployee){ Connectionconn=null; Statementstat=null; //1.注册驱动程序 try{ //2.获取连接 conn=JdbcUtil.getConnection(); //3.创建执行语句,发送sql命令 stat=conn.createStatement(); SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-dd"); Stringsql="updateempsetename='"+employee.getEname()+"',sal="+employee.getSal()+",hiredate='" +sdf.format(employee.getHiredate())+"'whereempno="+employee.getEmpno(); //4.处理执行结果 inti=stat.executeUpdate(sql); }catch(Exceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); }finally{ //5.关闭资源 JdbcUtil.free(conn); } } publicstaticvoiddeleteEmployee(intempno){ Connectionconn=null; Statementstat=null; //1.注册驱动程序 try{ //2.获取连接 conn=JdbcUtil.getConnection(); //3.创建执行语句,发送sql命令 stat=conn.createStatement(); SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-dd"); Stringsql="deletefromempwhereempno="+empno; //4.处理执行结果 inti=stat.executeUpdate(sql); }catch(Exceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); }finally{ //5.关闭资源 JdbcUtil.free(conn); } } }
这样看上去就比较清晰和明了,不用分割开来去看代码,只要调用到那个累才去照这个类的方法,这样就能够更加有利于检查和排错,维护的间接性的一个软件的奋斗的目标,虽然只是简单的优化,却能够减轻了我们写代码和维护的成本。
总结
通过本次编码,对面向对象的编程的开发有更加清晰的了解,当然对重构和优化的重要性有更深的了解,在这个软件里我学会的不仅是代码的书写,还学会了代码的重构不仅需要不断的提炼,还需要对代码的细微的观察。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。