jdbc访问数据库的具体步骤:
a.导入驱动,加载具体的驱动类
b.与数据库建立连接
c.发送sql,执行
d.处理结果集(集中)
a.导入驱动包、加载具体驱动类 Class.forName("com.mysql.cj.jdbc.Driver");
b.与数据库建立连接 connection = DriverManager.getConnection(....);
c.通过connection,获取操作数据库的对象(Statement \ preparedStatement \ callablestatement)
stmt = connection.createStatement();
d.(查询)处理结果集 rs = pstmt.executeQuery()
推荐使用PreparedStatement:原因如下:
1.编码更加简便 (避免了字符串的拼接)
String name = "zs";
int age = 23;
stmt:
String sql = "insert into student (stuno,stuname) values ('"+name+"',"+age+")" ;
stmt.executeUpdate(sql) ;
pstmt:
String sql = "insert into student (stuno,stuname) values (?,?)" ;
pstmt = connection.prepareStatement(sql); //预编译
pstmt.setString(1,name);
pstmt.setInt(2,age);
pstmt.executeUpdate();
2.提高性能 (因为有预编译操作, 预编译只需要执行一次)
需要重复增加100条数 (批量处理)
stmt:
String sql = "insert into student (stuno,stuname) values ('"+name+"',"+age+")" ;
stmt.executeUpdate(sql) ;
pstmt:
String sql = "insert into student (stuno,stuname) values (?,?)" ;
pstmt = connection.prepareStatement(sql); //预编译
pstmt.setString(1,name);
pstmt.setInt(2,age);
pstmt.executeUpdate();
3.安全(可以有效防止sql注入)
sql注入:将客户输入的内容 和 开发人员的SQL语句 混为一体
stmt:存在被sql注入的风险
(例如输入 用户名: 任意值 ' or 1=1 --
密码 : 任意值)
分析:
select count(*) from login where uname = '"+name+" ' and upwd = '"+pwd+";
select count(*) from login where uname = '任意值' or 1=1 -- ' and upwd = '任意值'; // --是sql的注释语句
select count(*) from login where uname = '任意值' or 1=1;
select count(*) from login ;
pstmt:有效防止sql注入
推荐使用pstmt