(在上一篇文章中,我们详细的介绍了连接数据库的方法,以及eclipse操作数据库信息的相关方法,在这里我们将主要讲封装。)
主要内容:
一般的连接数据库测试把连接数据库的方法封装成一个类和测试一个简单的插入表实例查询数据实例封装查询的数据库的信息封装信息后的查询数据库一.一般的数据库连接测试
1publicclassTestConnection1 {2publicstaticvoidmain(String[] args)throwsException {3Class.forName("com.MySQL.jdbc.Driver");4String url="jdbc:mysql://localhost:3306/test?"//数据库url5+ "useUnicode=true&characterEncoding=UTF8";//防止乱码6String user="h4";7String pass="111";8Connection conn=DriverManager.getConnection(url, user, pass);910System.out.PRintln(conn+",成功连接数据库");11conn.close();12}13}
二.我们不可能每写一个处理信息功能就写一次连接,这样太麻烦,那么为了方便以后的应用,我们通常把数据库连接封装起来。
具体实现步骤如下:
1.定义变量:
private static String DRIVER_CLASS;
private static String URL;
private static String USERRNAME;
private static String PASSWord;
2.在你建的eclipse根目录下新建一个File文件Properties;
文件内容为你定义的变量所指向的对象:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test? useUnicode=true&characterEncoding=UTF8
user=h4
pass=111
3.构建一个Properties对象:Properties p=new Properties();
4.java.io下的类FileInputStream的方法;FileInputStream(String name) :通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的路径名 name 指定。
来获取这个文件里面的资料:FileInputStream fis=new FileInputStream("db.properties");
5. 用3构建的变量p来下载资料:p.load(fis);
6.利用getProperty();获取参数:
DRIVER_CLASS=p.getProperty("driver");
URL=p.getProperty("url");
USERRNAME=p.getProperty("user");
PASSWORD=p.getProperty("pass");
7.写一个连接数据库的方法getConection();
8.写一个关闭数据库的方法close(Connection conn);
写好后代码如下:
1publicclassjdbcutil {2privatestaticString DRIVER_CLASS;3privatestaticString URL;4privatestaticString USERRNAME;5privatestaticString PASSWORD;6privatestaticProperties p=newProperties();7static{8try{9FileInputStream fis=newFileInputStream("db.properties");10p.load(fis);11DRIVER_CLASS=p.getProperty("driver");12URL=p.getProperty("url");13USERRNAME=p.getProperty("user");14PASSWORD=p.getProperty("pass");15Class.forName(DRIVER_CLASS);16fis.close();17}catch(IOException e) {18e.printStackTrace();19}catch(ClassNotFoundException e) {20e.printStackTrace();21}22}23publicstaticConnection getConection(){24Connection conn=null;25try{26conn=DriverManager.getConnection(URL, USERRNAME, PASSWORD);27}28catch(Exception e) {29e.printStackTrace();30}31returnconn;32}33publicstaticvoidclose(Connection conn) {34try{35if(conn !=null)36conn.close();37}catch(Exception e) {38e.printStackTrace();39}40}4142}
那么封装好之后,我们来写一个测试类,测试连接
1publicclassTestConnection2 {23publicstaticvoidmain(String[] args)throwsException {4Connection conn=jdbcutil.getConection();//利用封装好的类名来调用连接方法便可5System.out.println(conn+",成功连接数据库");6jdbcutil.close( conn);//同样利用类名调用关闭方法即可7}8}
三.连接成功,我们写一个简单的向数据库插入表的实例。
1publicclassTestDDl {23publicstaticvoidmain(String[] args) {4Connection conn=null;5Statement stmt=null;6conn=jdbcutil.getConection();//连接数据库7String createTableSql= " create table user_test1( "+//记住引号和单词间一定要有空格8" id int, "+9" name varchar(32) , "+10" password varchar(32) , "+11" birthday date "+12" ) ";13try{14stmt=conn.createStatement();15stmt.execute(createTableSql);16}catch(SQLException e) {17e.printStackTrace();18}19jdbcutil.close(null, stmt, conn);//关闭数据库20}21}
四.我们在写一个查询数据库数据的实例。(有三种方法)
1publicclassTestDQL {2publicstaticvoidmain(String[] args){3Connection conn=null;//定义为空值4Statement stmt=null;5ResultSet rs=null;6String sql="select * from employees";//sql语句7conn=jdbcutil.getConection();8try{9stmt=conn.createStatement();//创建一个Statement语句对象10rs=stmt.executeQuery(sql);//执行sql语句11while(rs.next()){12System.out.print(rs.getInt(1)+",");13System.out.print(rs.getString(2)+",");//直接使用参数14System.out.print(rs.getString(3)+",");15System.out.print(rs.getString(4)+",");16System.out.println(rs.getString(5));17}18}catch(SQLException e) {19e.printStackTrace();20}finally{21jdbcutil.close(rs,stmt,conn);//关闭数据库22}23}24}
//第二种方法如下:
1publicclassTestDQl2 {23publicstaticvoidmain(String[] args) {4Connection conn=null;5Statement stmt=null;6ResultSet rs=null;7String sql="select * from employees";8conn=jdbcutil.getConection();9try{10stmt=conn.createStatement();11rs=stmt.executeQuery(sql);12while(rs.next()){13System.out.print(rs.getInt("userid")+",");//里面直接写要查找的内容名称14System.out.print(rs.getString("employee_id")+",");15System.out.print(rs.getString("last_name")+",");16System.out.print(rs.getString("salary")+",");17System.out.println(rs.getString("department_id"));18}19}catch(SQLException e) {20e.printStackTrace();21}finally{22jdbcutil.close(rs,stmt,conn);23}24}25}
1//第三种方法如下:2publicclassTestDQL3 {3publicstaticvoidmain(String[] args) {4Connection conn=null;5Statement stmt=null;6ResultSet rs=null;7String sql="select * from employees";8conn=jdbcutil.getConection();9try{10stmt=conn.createStatement();11rs=stmt.executeQuery(sql);12while(rs.next()){13intindex=1;14System.out.print(rs.getInt(index++)+",");15System.out.print(rs.getString(index++)+",");16System.out.print(rs.getString(index++)+",");17System.out.print(rs.getString(index++)+",");18System.out.println(rs.getString(index++));19}20}catch(SQLException e) {21e.printStackTrace();22}finally{23jdbcutil.close(rs,stmt,conn);24}25}26}
五.在四里面我们写了查询员工资料的信息,但是有的时候我们要保存起来方便之后更好的查找,那怎么办呢?没错,封装。
1publicclassemployeesimplementsSerializable {2privateInteger userid;3privateString employee_id;4privateString last_name;5privateString salary;6privateString department_id;78publicemployees() {9super();10}1112publicemployees(String employee_id, String last_name, String salary, String department_id) {13super();14this.employee_id =employee_id;15this.last_name =last_name;16this.salary =salary;17this.department_id =department_id;18}1920@Override21publicString toString() {22return"employees [userid=" + userid + ", employee_id=" + employee_id + ", last_name=" +last_name23+ ", salary=" + salary + ", department_id=" + department_id + "]";24}2526publicInteger getUserid() {27returnuserid;28}2930publicvoidsetUserid(Integer userid) {31this.userid =userid;32}3334publicString getEmployee_id() {35returnemployee_id;36}3738publicvoidsetEmployee_id(String employee_id) {39this.employee_id =employee_id;40}4142publicString getLast_name() {43returnlast_name;44}4546publicvoidsetLast_name(String last_name) {47this.last_name =last_name;48}4950publicString getSalary() {51returnsalary;52}5354publicvoidsetSalary(String salary) {55this.salary =salary;56}5758publicString getDepartment_id() {59returndepartment_id;60}6162publicvoidsetDepartment_id(String department_id) {63this.department_id =department_id;64}65}
六.封装好后的查询和上面没封装之前有点变化。
1publicclassTestDQL4 {2publicstaticvoidmain(String[] args) {3Connection conn=null;4Statement stmt=null;5ResultSet rs=null;6List<employees> emps=newArrayList<>();//构造集合对象78String sql="select * from employees";910conn=jdbcutil.getConection();//获取数据库连接1112try{13stmt=conn.createStatement();14rs=stmt.executeQuery(sql);15while(rs.next()){//遍历结果集16intindex=1;17employees emp=newemployees();//构造员工类对象18emp.setUserid(rs.getInt(index++));//获取值19emp.setEmployee_id(rs.getString(index++));20emp.setLast_name(rs.getString(index++));21emp.setSalary(rs.getString(index++));22emp.setDepartment_id(rs.getString(index++));23emps.add(emp);//放到集合中去24}25}catch(SQLException e) {26e.printStackTrace();27}finally{28jdbcutil.close(rs,stmt,conn);//关闭连接29}30for(employees emp:emps){//遍历31System.out.println(emp);32}33}34}
其实我们可以继续封装,把遍历结果集给封装起来。
1publicclassTestDQL5 {23publicstaticvoidmain(String[] args) {4Connection conn=null;5Statement stmt=null;6ResultSet rs=null;7List<employees> emps=newArrayList<>();89String sql="select * from employees";1011conn=jdbcutil.getConection();1213try{14stmt=conn.createStatement();15rs=stmt.executeQuery(sql);16emps=resultSetToEmployees(rs);17}catch(SQLException e) {18e.printStackTrace();19}finally{20jdbcutil.close(rs,stmt,conn);21}22for(employees emp:emps){23System.out.println(emp);24}25}26publicstaticList<employees>resultSetToEmployees(ResultSet rs){27List<employees> emps=newArrayList<>();28try{29while(rs.next()){30intindex=1;31employees emp=newemployees();32emp.setUserid(rs.getInt(index++));33emp.setEmployee_id(rs.getString(index++));34emp.setLast_name(rs.getString(index++));35emp.setSalary(rs.getString(index++));36emp.setDepartment_id(rs.getString(index++));37emps.add(emp);38}39}catch(SQLException e) {40e.printStackTrace();41}4243returnemps;44}45}
如果是一个人查询信息呢?还可以这样封装。
1publicclassTestDQL6 {2publicstaticvoidmain(String[] args) {3Connection conn=null;4Statement stmt=null;5ResultSet rs=null;6List<employees> emps=newArrayList<>();78String sql="select * from employees";910conn=jdbcutil.getConection();1112try{13stmt=conn.createStatement();14rs=stmt.executeQuery(sql);15while(rs.next()){16employees emp=resultSetToEmployee(rs);17emps.add(emp);18}19}catch(SQLException e) {20e.printStackTrace();21}finally{22jdbcutil.close(rs,stmt,conn);23}24for(employees emp:emps){25System.out.println(emp);26}27}28publicstaticemployees resultSetToEmployee(ResultSet rs){29employees emp=null;30try{31intindex=1;32emp=newemployees();33emp.setUserid(rs.getInt(index++));34emp.setEmployee_id(rs.getString(index++));35emp.setLast_name(rs.getString(index++));36emp.setSalary(rs.getString(index++));37emp.setDepartment_id(rs.getString(index++));38}catch(SQLException e) {39e.printStackTrace();40}41returnemp;42}43}