失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > JDBC数据对象存储

JDBC数据对象存储

时间:2019-12-12 10:29:29

相关推荐

JDBC数据对象存储

一:将查询的结果生成对象,储存在数组中。

1 package day31; 2 3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 import java.util.ArrayList; 8 9 public class java_obj {10public static void main(String[] args)throws SQLException{11 Connection con=jdbcutils.getCon();12 PreparedStatement pst=con.prepareStatement("select * from system_user");13 ResultSet res=pst.executeQuery();14 /*15 将查询的结果用泛型数组储存。16*/17 ArrayList<System_user> sys_list=new ArrayList<>();18 while (res.next()){19 System_user sys_u=new System_user(res.getString("username"),res.getString("password"));20 sys_list.add(sys_u);21 }22 System.out.print(sys_list);23 jdbcutils.cls_re(con,pst,res);24}25 }26 27 28 class System_user{29private String user;30private String pwd;31public System_user(String user, String pwd){32 this.user=user;33 this.pwd=pwd;34}35 36@Override37public String toString() {38 return this.user+" "+this.pwd;39}40 }

工具类:

1 package day31; 2 3 import java.sql.*; 4 5 public class jdbcutils { 6/* 7创建jdbc工具类。 81:方便别人调用 92:避免代码重复。10*/11private jdbcutils(){}//工具类不需要实例化,所以方法进行私有化。12private static Connection con;//需要静态变量13 14/*15静态代码块在加载类的时候就执行该部分的代码。16*/17static {18 try{19 Class.forName("com.mysql.jdbc.Driver");20 String url="jdbc:mysql://192.168.147.146:3306/homework_day13";21 String username="test";22 String password="123456";23 con= DriverManager.getConnection(url,username,password);24 }catch (Exception ex){25 throw new RuntimeException(ex+"数据库连接失败!");//如果出现异常的话 需要种子程序 所以要抛出异常。需要创建运行异常的错误。26 }27}28 29public static Connection getCon(){30 return con;31}32/*33关闭资源。34通过方法的重载来判断用户执行的是查询和更新操作。35*/36public static void cls_re (Connection con, Statement pst, ResultSet rs)throws SQLException{37 /*38 注意:这里需要判断需要关闭的对象是否存在以及该对象如果抛出异常不能影响下面的关闭。39 这里是Statement 是prepareStament的父类。40*/41 if(con!=null){42 try {43 con.close();44 }catch (Exception ex){}45 }46 if(pst!=null){47 try {48 pst.close();49 }catch (Exception ex){}50 }51 if(rs!=null){52 try {53 rs.close();54 }catch (Exception ex){}55 }56 57}58public static void cls_re(Connection con,Statement pst){59 if(pst!=null){60 try {61 pst.close();62 }catch (Exception ex){}63 }64 if(pst!=null){65 try {66 pst.close();67 }catch (Exception ex){}68 }69}70 }

如果觉得《JDBC数据对象存储》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。