使用properties文件配置数据库驱动,uri,用户名和密码;以便于日后更换数据库不用更改源代码;
driver=com.mysql.jdbc.Driveruri=jdbc:mysql://localhost:3306/day10user=rootpassword=root
1.注册驱动
1 public static Connection getConn() throws FileNotFoundException, IOException, ClassNotFoundException, SQLException{2 3 Class.forName(prop.getProperty("driver"));4 return DriverManager.getConnection(prop.getProperty("uri"),prop.getProperty("user"),prop.getProperty("password"));5 6 7 }
2.创建连接器
Connection conn = JDBCUtils.getConn();//Connection conn = DriverMananger("uri,user,password");
3.获取传输器
Statment stat = conn.createStatement();
5.利用传输器查询语句,并返回结果集
stat.executeUpdate(sql); 增删改
stat.executeQuery(sql);查询语句
6.关闭资源
1 public static void close(Connection conn,Statement stat,ResultSet rs){ 2 3 if(rs!=null){ 4 try { 5 rs.close(); 6 } catch (SQLException e) { 7 throw new RuntimeException(e); 8 9 }finally{10 rs=null;11 }12 }13 if(stat!=null){14 try {15 stat.close();16 } catch (SQLException e) {17 throw new RuntimeException(e);18 19 }finally{20 stat=null;21 }22 }23 if(conn!=null){24 try {25 conn.close();26 } catch (SQLException e) {27 throw new RuntimeException(e);28 29 }finally{30 conn=null;31 }32 }33 }
最后 使用预编译语句可防止SQL语句的注入问题,preparestatment
1 String sql = "select * from user where username=?and password =?";2 ps = conn.prepareStatement(sql);3 ps.setString(1, username);4 ps.setString(2, password);5 rs = ps.executeQuery();