41.1. 回顾
1. jdbc:[java database connection] java连接数据库
2. 完成了增删改操作。
[1]加载驱动。Class.forName("com.mysql.cj.jdbc.Driver");
[2]获取连接对象: Connection conn=DriverManager.getConnection(url,user,pass);
url: jdbc:mysql://localhost:3306/数据库名?serverTimezone=Asia/Shanghai
[3]获取执行sql语句的对象: Statement st=conn.createStatement();
[4]执行sql语句: st.executeUpdate(sql);
sql: 增删改的sql.
修改: update 表名 set 字段名=值,字段名=值.... where 条件
添加: insert into 表名 values(值,值....);
删除: delete from 表名 where 条件
[5]关闭资源
41.2. 正文
目录
41.1. 回顾
41.2. 正文
41.3 查询-所有
41.4 异常处理
41.5 sql注入安全问题
41.6企业级开发的模式
41.3 查询-所有
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;public class Test02 {public static void main(String[] args) throws Exception{//1. 加载驱动Class.forName("com.mysql.cj.jdbc.Driver");//2.获取连接对象String url="jdbc:mysql://localhost:3306/mydb";String user="root";String password="root";Connection conn= DriverManager.getConnection(url,user,password);//3.获取执行sql的对象Statement st=conn.createStatement();//4. 执行sql语句String sql="select * from tbl_emp";//把查询的结果封装到一个ResultSet对象中。ResultSet rs = st.executeQuery(sql);//5. 从resultSet中取出结果. next():指针往下移动并判断当前是否存在元素。 getXXX();获取当前行的指定列的值。while(rs.next()){System.out.println(rs.getInt("id")+"\t"+rs.getString("name")+"\t"+rs.getDouble("salary"));}//6. 关闭资源rs.close();st.close();conn.close();}
}
根据用户名查询: 查询姓李的人。
package com.demo01;import java.sql.*;public class Test05 {public static void main(String[] args) throws Exception {query();}public static void query() throws Exception {Class.forName("com.mysql.cj.jdbc.Driver");String url = "jdbc:mysql://localhost:3306/day112303";String user = "root";String password = "634835";Connection conn = DriverManager.getConnection(url, user, password);Statement statement = conn.createStatement();String sql = "SELECT * FROM student WHERE s_name LIKE '李%'";statement.executeQuery(sql);ResultSet rs = statement.executeQuery(sql);while (rs.next()) {System.out.println(rs.getInt("s_id") + "\t" + rs.getString("s_name"));}}
}
41.4 异常处理
import java.sql.*;public class Test02 {public static void main(String[] args) {Connection conn = null;Statement st = null;ResultSet rs = null;try {//1. 加载驱动Class.forName("com.mysql.cj.jdbc.Driver");//2.获取连接对象String url = "jdbc:mysql://localhost:3306/mydb";String user = "root";String password = "root";conn = DriverManager.getConnection(url, user, password);//3.获取执行sql的对象st = conn.createStatement();//4. 执行sql语句String sql = "select * from tbl_emp";//把查询的结果封装到一个ResultSet对象中。rs = st.executeQuery(sql);//5. 从resultSet中取出结果. next():指针往下移动并判断当前是否存在元素。 getXXX();获取当前行的指定列的值。while (rs.next()) {System.out.println(rs.getInt("id") + "\t" + rs.getString("name") + "\t" + rs.getDouble("salary"));}} catch (Exception e) {e.printStackTrace();} finally {//6. 关闭资源if (rs != null) {try {rs.close();} catch (SQLException throwables) {throwables.printStackTrace();}}if (st != null) {try {st.close();} catch (SQLException throwables) {throwables.printStackTrace();}}if (conn != null) {try {conn.close();} catch (SQLException throwables) {throwables.printStackTrace();}}}}
}
41.5 sql注入安全问题
发现无论你输入任何的账户和密码 只要or 后面的条件成立,
那么一定都可以登录成功。出现bug了。
问题出现在Statement类,该类存在sql注入安全隐患。
为了解决该隐患,创建了一个子类PreparedStatement.
import java.sql.*;
import java.util.Scanner;public class Test03 {static String url = "jdbc:mysql://localhost:3306/mydb";static String user = "root";static String pwd = "root";public static void main(String[] args) {Scanner sc=new Scanner(System.in);System.out.print("请输入账户:");String u=sc.nextLine();System.out.print("请输入密码:");String p=sc.nextLine();// next()和nextLine()区别: next()输入空格 空格以后的内容无法获取boolean flag = login(u, p);if(flag==true){System.out.println("登录成功");}else{System.out.println("登录失败");}}/*** 根据账户和密码判断是否登录成功** @param name 输入的账户* @param password 输入的密码* @return true表示登录成功 false表示登录失败*/public static boolean login(String name, String password) {Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;try {Class.forName("com.mysql.cj.jdbc.Driver");conn = DriverManager.getConnection(url, user, pwd);//?:表示占位符。--对sql预先编译。String sql = "select * from tbl_user where username=? and password=?";ps = conn.prepareStatement(sql);//为占位符赋值。int parameterIndex 第几个占位符, Object x 占位符的内容ps.setObject(1,name);ps.setObject(2,password);rs = ps.executeQuery();while (rs.next()) {return true;}} catch (Exception e) {e.printStackTrace();} finally{//6. 关闭资源if (rs != null) {try {rs.close();} catch (SQLException throwables) {throwables.printStackTrace();}}if (ps != null) {try {ps.close();} catch (SQLException throwables) {throwables.printStackTrace();}}if (conn != null) {try {conn.close();} catch (SQLException throwables) {throwables.printStackTrace();}}}return false;}}
根据账户和年龄查询用户信息 使用preparedStatement
41.6企业级开发的模式
dao类:
[data access object ] 数据访问对象层
该包下的类都是用来访问数据对应表的操作。
StudentDao: 该类专门用来操作Student表的,每个操作对应一个方法。
TeacherDao: 该类专门用来操作Teacher表,每个操作对应一个方法。
package com.ykq.dao;import java.sql.*;public class UserDao {String url = "jdbc:mysql://localhost:3306/mydb";String user = "root";String pwd = "root";Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;//每个操作对应一个方法。//1.根据id删除用户public int deleteById(int id) {try {Class.forName("com.mysql.cj.jdbc.Driver");conn = DriverManager.getConnection(url, user, pwd);//?:表示占位符。--对sql预先编译。String sql = "delete from tbl_user where id=?";ps = conn.prepareStatement(sql);ps.setObject(1,id);int i = ps.executeUpdate();return i;} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException throwables) {throwables.printStackTrace();} finally {//6. 关闭资源if (rs != null) {try {rs.close();} catch (SQLException throwables) {throwables.printStackTrace();}}if (ps != null) {try {ps.close();} catch (SQLException throwables) {throwables.printStackTrace();}}if (conn != null) {try {conn.close();} catch (SQLException throwables) {throwables.printStackTrace();}}}return 0;}//2. 添加用户public int insert(String username,String password,String realname){try {Class.forName("com.mysql.cj.jdbc.Driver");conn = DriverManager.getConnection(url, user, pwd);//?:表示占位符。--对sql预先编译。String sql = "insert into tbl_user(username,password,realname) values(?,?,?)";ps = conn.prepareStatement(sql);ps.setObject(1,username);ps.setObject(2,password);ps.setObject(3,realname);//执行sqlint i = ps.executeUpdate();return i;} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException throwables) {throwables.printStackTrace();} finally {//6. 关闭资源if (rs != null) {try {rs.close();} catch (SQLException throwables) {throwables.printStackTrace();}}if (ps != null) {try {ps.close();} catch (SQLException throwables) {throwables.printStackTrace();}}if (conn != null) {try {conn.close();} catch (SQLException throwables) {throwables.printStackTrace();}}}return 0;}
}