JDBCコードのショーを実現するのprepareStatement
import java.sql.*;
public class Main {//com.mysql.cj.jdbc.Driver
private static final String URL="jdbc:mysql://localhost:3306/student?serverTimezone=UTC";
private static final String USERNAME="yucan";
private static final String PASSWORD="1234";
public static void update(){ //增删改
Connection connection=null;
PreparedStatement pstatement=null;
try{
//a.导入驱动。加载具体的驱动类
Class.forName( "com.mysql.cj.jdbc.Driver" );
//b.建立连接
connection=DriverManager.getConnection( URL,USERNAME,PASSWORD );
//发送sql,执行
String sql="insert into id values(?,?)";
pstatement=connection.prepareStatement( sql );
pstatement.setString( 1,"24" );
pstatement.setString( 2,"21" );
int count=pstatement.executeUpdate();
//注意:这个地方不用添加参数sql
if(count>0){
System.out.println( "执行成功!" );
}
}catch (ClassNotFoundException e){
e.printStackTrace();
}catch (SQLException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
finally {
try {
if(pstatement!=null)
pstatement.close();
if(connection!=null)
connection.close();
}catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
update();
}
}
prepareStatementステートメントは、サブクラスで
次のように差があり、比較:
1.比較的速い;
2実施形態は、注入をSQLできます
I.すぐに
起因するのprepareStatementはそう繰り返し同じSQL文を実行したときにコンパイルされていない、だけで実行することができ、プリコンパイルされた関数を持っていますが、それぞれの実行文、我々は、操作をコンパイルする必要があります。
文の例:
文字列のSQL = "INSERT INTO学生(stuno、stuname)の値( '" +名+ "'、" +年齢+ ")";
Statement.executeUpdate(SQL);
PreparedStatementの例:
文字列のSQL = "INSERT INTO学生(ID 、パスワード)の値(、)?? ";
のprepareStatement =のConnection.prepareStatement(SQL); //コンパイル済み
prepareStatement.setInt(1,23);
preparestatement.setString(2、" dsfdfad「)。
第防止SQLインジェクション
文:
SQL注入されるリスク
(任意値:ユーザー名:任意の値「または1 = 1--パスワード例えば入力)
分析:
SELECT COUNT(*)ログインのuname = 『任意の値』からOR1 = 1 - 「とのuserpassword = 」 任意の値「この式が真で一定である
のprepareStatementを
効果的に防止することができるSQLインジェクション