import java.sql.*;
public class JDBCConnect02 {
public static void main(String[] args) {
loginSystem("02","02 OR' 1 '=' 1");
}
public static void loginSystem(String uname, String upassword) {
Connection connection = null; //用于和数据库的连接
PreparedStatement preparedStatement = null;//用于发送对数据库的请求,进行数据库的增删改查操作
ResultSet resultSet = null;//用于获取返回的数据
try {
// 1、注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");// 使用什么驱动连接数据库
// 创建数据库连接
String url = "jdbc:mysql://localhost:3306/test_db_char?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8";
// 用户名和密码
String user = "root";
String password = "123456";
// 2、跟数据库建立连接(得到链接) DruverManager返回的事java.sql下面的 所以Connection也是用javasql下面的
connection = DriverManager.getConnection(url, user, password);
//防止sql注入问题
//步骤一:先创建sql查询语句
String sql = "SELECT * FROM tb_students_info WHERE username=? AND password=?";
//步骤二:创建PreparedStatement
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, uname);
preparedStatement.setString(2, upassword);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
//通过列的索引获取表中的数据
System.out.println(resultSet.getInt(1) + "-"
+ resultSet.getString(2) + "-"
+ resultSet.getString(3) + "-"
+ resultSet.getString(4) + "-"
+ resultSet.getInt(5) + "-"
//指定获取对象的列
+ resultSet.getInt(6) + "-"
+ resultSet.getBoolean(7) + "-"
//指定返回对象的类型
+ resultSet.getObject(8, int.class) + "-"
+ resultSet.getBigDecimal(9)+ "-"
//指定获取对象的字段名称
+ resultSet.getDate("login_date")
);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
// 上面是分别获取了抛出的异常,还可以直接获取所有的异常
catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (resultSet != null)
resultSet.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (preparedStatement != null)
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (connection != null)
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
防止sql注入问题
猜你喜欢
转载自blog.csdn.net/qq_45968950/article/details/121914777
今日推荐
周排行