package csdn1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.Test;
public class jdbc3 {
// 执行sql,一种是Statement,一种是PrepareStatemnt
/*
* 1.PrepareStatement 使用参数设置,可读性好,不易犯错(防止sql注入)
* 与创建Statement不同的是,需要根据sql语句创建PrepareStatement
* (通过设置参数,指定相应的值,而不是像Statement那样使用字符串拼接)
*
* 2.PrepareStatement有预编译机制,性能比Statement更快
* 对于执行多次同一条sql语句,Statement执行需要多次把sql语句传给数据库端,数据库进行多次编译处理。
* 但PrepareStatement只需传一次sql语句给数据库端,数据库对?的sql进行预编译,
* 每次执行,只需传输参数到数据库端,1.网络传输量减小、2数据库不需要再进行编译,响应快。
*
* 但不同sql语句需要创建多个对象
*/
@Test
public void problem() {
// sql注入问题:
// 这里由于where后面的条件为永真,导致所有数据都被查询出来,这对于海量数据来说将会极耗内存,导致响应变慢
jdbc3 j = new jdbc3();
try (Connection c = j.getConnection();) {
String name = "zl' or '1=1";// 假设这是用户的输入,虽然这种可能性小,但确实是个问题
String sql = "select * from user where name = '" + name + "';";
Statement cs = c.createStatement();
ResultSet set1 = cs.executeQuery(sql);
while (set1.next()) {
System.out.println(set1.getString(3));
}
System.out.println("------------------------");
sql = "select * from user where name = ?";
PreparedStatement ps = c.prepareStatement(sql);
ps.setString(1, name);
ResultSet set2 = ps.executeQuery();
while (set2.next()) {
System.out.println(set2.getString(3));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
// prepareStatement使用1
@Test
public void update() {
String sql = "insert into user (name,password) values(?,?);";
jdbc3 j = new jdbc3();
Connection c = j.getConnection();
try (PreparedStatement prepareStatement = c.prepareStatement(sql);) {
// 参数设置
prepareStatement.setString(1, "zl");
prepareStatement.setString(2, "zl679");
int num = prepareStatement.executeUpdate();
System.out.println(num);
// 补: 插入时,可获取当前的自增长id
ResultSet keys = prepareStatement.getGeneratedKeys();// 也可以通过statement获取,效果一样
while (keys.next()) {
String str1 = keys.getString(1);
String str2 = keys.getString("GENERATED_KEY");// 自增长id的名字
System.out.println(str1 + " == " + str2);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
// prepareStatement使用2
@Test
public void query() {
String sql = "select count(*) from user;";
jdbc3 j = new jdbc3();
Connection c = j.getConnection();
try (PreparedStatement prepareStatement = c.prepareStatement(sql);) {
ResultSet set = prepareStatement.executeQuery();
System.out.println(set);
if (set.next()) {
System.out.println(set.getString(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 获取连接
*
* @return
*/
public Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String url = "jdbc:mysql://localhost:3306/mydbs2";
Connection connection = null;
try {
connection = DriverManager.getConnection(url, "root", "root");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
}
版权声明:本文为qq_45833812原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。