Statement will have a bug about SQL injection, so I don't use
General use PreparedStatement
Import java.sql.Connection;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;
Import Com.huawei.utils.DBUtil;
public class TestJDBC02 {
public static void Testpreparedstatement () throws exception{
/**
* Preprocessing SQL statements does not present a bug with SQL injection
*/
Connection Connection = Dbutil.getconnection ();
String sql = "SELECT * from Users where username=?";
Getting preprocessing objects for SQL statements
PreparedStatement preparedstatement = connection.preparestatement (sql);
Preparedstatement.setobject (1, "admin1 ' or 1=1 or username= '");
ResultSet rs = Preparedstatement.executequery ();
while (Rs.next ()) {
System.out.println (Rs.getobject (1));
}
Dbutil.close (rs,preparedstatement,connection);
}
public static void Testtransaction () throws exception{
Connection Connection = Dbutil.getconnection ();
Default transactions are auto-committed
Auto-commit must be turned off to achieve the purpose of manual submission
Connection.setautocommit (FALSE);
PreparedStatement PS = null;
PreparedStatement PS1 = null;
try{
PS = connection.preparestatement ("INSERT into a (a) values (' lisi21 ')");
PS1 = Connection.preparestatement ("INSERT into B (b) VALUES (' lisi123 ')");
Ps.executeupdate ();
Ps1.executeupdate ();
Commit to database after execution completes
Connection.commit ();
}catch (Exception e) {
Rollback if any errors are generated
Connection.rollback ();
E.printstacktrace ();
}
Dbutil.close (ps,ps1,connection);
}
public static void Main (string[] args) throws Exception {
Testtransaction ();
}
}
SQL injection and transaction