1、什么是jdbc
Java数据库连接,由一些接口和类构成的API(Application Programming Interface,应用程序编程接口),java对外提供数据库连接的接口,各个数据库厂商提供连接时的实现类(驱动),实现java和数据库的连接
jdbc作用:是java程序和数据库之间的桥梁
应用程序,jdbcAPI,数据库驱动及数据库之间的关系
2、jdbc开发步骤
package com.zy.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import org.junit.Test; public class MyJDBC { public static void main(String[] args) throws Exception { // jdbc是连接数据库一种技术 //程序——>数据库 //八股文编程法----顺序要求明显,不要自由发挥 //1加载驱动 //该复制的不要手写,所有bug都是手写出来的 Class forName = Class.forName("com.mysql.jdbc.Driver"); //2建立连接 ip 端口 数据库名 String url="jdbc:mysql://localhost:3306/data75"; Connection connection = DriverManager.getConnection(url, "root", "123456"); if(!connection.isClosed()){ System.out.println("Succeeded connecting to the Database!"); } //3准备sql String sql="select * from student"; //4得到执行对象 Statement st = connection.createStatement(); //5执行得到结果集 ResultSet rs = st.executeQuery(sql); //6遍历结果集 while(rs.next()){//结果集如果取下一行已经到头返回false int id = rs.getInt(1); String name = rs.getString(2); String sex = rs.getString(3); String birth = rs.getString(4); String department = rs.getString(5); String address = rs.getString(6); System.out.println(name+" "+sex+" "+birth+" "+department+" "+address); } //7关闭资源(先开后关) rs.close(); st.close(); connection.close(); } }
3、sql注入风险
Scanner sc = new Scanner(System.in); System.out.println("请输入用户名"); String name = sc.nextLine(); System.out.println("请输入密码"); String pwd =sc.nextLine(); //1加载驱动 Class.forName("com.mysql.jdbc.Driver"); //2得到连接 Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/data75", "root", "123456"); //3准备一个sql // String sql="SELECT * FROM user WHERE name='"+name+"' AND password='"+pwd+"'"; // 4得到执行对象 // Statement st = connection.createStatement(); // 5执行查询 // ResultSet rs = st.executeQuery(sql); // rs.next()向下获取一行数据 如果到末尾返回false // if(rs.next()){ // System.out.println("登录成功"); // // }else{ // System.out.println("登录失败"); // // } //6关闭资源 // rs.close(); // st.close(); // connection.close(); //------------------------------------------------------ //Statement 存在sql注入的风险所以prepareStatement 准备/预编译的 //占位符?-----替代了原始的字符串拼接 //3 sql String sql="SELECT * FROM user WHERE name=? AND password=?"; //4得到执行对象 PreparedStatement ps = connection.prepareStatement(sql); //5设置占位符参数 1表示第一个问号 ps.setString(1, name);//传入的参数只会当做一个值,而不是拼接状态,跟+拼接不一样 ps.setString(2, pwd); //6执行 ResultSet rs = ps.executeQuery();//除了查询,其他都用executeUpdate //7判断 if(rs.next()){ System.out.println("登录成功"); }else{ System.out.println("登录失败"); } rs.close(); connection.close();
4、单元测试
//1 通过eclipse加入单元测试jar包 //2使用@Test注解 //单元测试----可以达到类似main方法的一个效果 @Test public void show(){ System.out.println("这里写单元测试"); } //删除 @Test public void delete() throws Exception{ Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/data75", "root", "123456"); String sql="DELETE FROM user WHERE name=?"; PreparedStatement ps = connection.prepareStatement(sql); ps.setString(1, "hello"); int executeUpdate = ps.executeUpdate(); System.out.println("执行后的返回值"+executeUpdate); ps.close(); connection.close(); } //更新 @Test public void update() throws Exception{ Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/data75", "root", "123456"); String sql="UPDATE USER SET NAME = ? WHERE id = ?"; PreparedStatement ps = connection.prepareStatement(sql); ps.setString(1, "小红"); ps.setString(2, "2"); int executeUpdate = ps.executeUpdate(); System.out.println("执行后的返回值"+executeUpdate); ps.close(); connection.close(); } //增加 @Test public void insert() throws Exception{ Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/data75", "root", "123456"); String sql="INSERT INTO user VALUES(NULL,?,?)"; PreparedStatement ps = connection.prepareStatement(sql); ps.setString(1, "hello"); ps.setString(2, "111"); int executeUpdate = ps.executeUpdate(); System.out.println("执行的返回值"+executeUpdate); ps.close(); connection.close(); }
5、将连接数据库包封装成JDBCUtil工具类
package com.zy.utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class JDBCutil { //静态代码块会在该类被使用时自动加载到内存,所以里面适合放一些初始化的代码 static{ try { //1加载驱动 Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static PreparedStatement getPreparedStatement(Connection connection,String url,String username,String password,String sql){ try { //2得到连接 connection = DriverManager.getConnection(url, username, password); //4得到执行对象 PreparedStatement ps = connection.prepareStatement(sql); return ps; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } //7关闭资源(static就是方便调用) public static void closeAll(ResultSet rs,Connection connection,PreparedStatement ps){ if(rs!=null){ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(ps!=null){ try { ps.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(connection!=null){ try { connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //根据id删除某条数据 public static void deleteById(PreparedStatement ps,int id){ try { ps.setInt(1,id); ps.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
@Test public void update2() throws Exception{ Connection connection=null; String url="jdbc:mysql://localhost:3306/data75"; String username="root"; String password="123456"; //3准备一个sql String sql="UPDATE USER SET NAME = ? WHERE id = ?"; PreparedStatement ps = JDBCutil.getPreparedStatement(connection, url, username, password, sql); //5设置占位符参数 ps.setString(1, "小明"); ps.setString(2, "2"); //6执行 ps.executeUpdate(); JDBCutil.closeAll(null, connection, ps); } @Test public void delete2() throws Exception{ Connection connection=null; String url="jdbc:mysql://localhost:3306/data75"; String username="root"; String password="123456"; String sql="DELETE FROM user WHERE id=?"; int id=4; PreparedStatement ps = JDBCutil.getPreparedStatement(connection, url, username, password, sql); JDBCutil.deleteById(ps, id); JDBCutil.closeAll(null, connection, ps); }