连接数据的步骤如下:
1.注册驱动
2.获取连接
3.创建执行sql语句的对象
4.书写一个SQL语句
5.执行SQL语句
6.对结果集进行处理
一下的这种情况,可能存在SQL注入的情况
public void login(String username, String password) throws ClassNotFoundException, SQLException { // 1.注册驱动 Class.forName("com.mysql.jdbc.Driver"); // 2.获取连接 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/web08", "root", "root"); // 3.创建执行sql语句的对象 Statement stmt = conn.createStatement(); // 4.书写一个sql语句 String sql = "select * from tbl_user where " + "uname='" + username + "' and upassword='" + password + "'"; // 5.执行sql语句 ResultSet rs = stmt.executeQuery(sql); // 6.对结果集进行处理 if (rs.next()) { System.out.println("恭喜您," + username + ",登录成功!"); System.out.println(sql); } else { System.out.println("账号或密码错误!"); } if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); }
PreparedStatement 解决了这种情况
public void login1(String username, String password) throws ClassNotFoundException, SQLException { // 1.注册驱动 Class.forName("com.mysql.jdbc.Driver"); // 2.获取连接 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/web08", "root", "root"); // 3.编写sql语句 String sql = "select * from tbl_user where uname=? and upassword=?"; // 4.创建预处理对象 PreparedStatement pstmt = conn.prepareStatement(sql); // 5.设置参数(给占位符) pstmt.setString(1, username); pstmt.setString(2, password); // 6.执行查询操作 ResultSet rs = pstmt.executeQuery(); // 7.对结果集进行处理 if (rs.next()) { System.out.println("恭喜您," + username + ",登录成功!"); System.out.println(sql); } else { System.out.println("账号或密码错误!"); } if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } }