mysql的prepareStatement執行sql可以去掉特殊字符'或/

廢話不多說,直接上demo
附帶了sql拼接的sqlBuffer.deleteCharAt API

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
 
public class InsertMorePreparedStatement {
 
    // MySQL 8.0 以下版本 - JDBC 驅動名及數據庫 URL
//    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
//    static final String DB_URL = "jdbc:mysql://localhost:3306/ewqq";
    // MySQL 8.0 以上版本 - JDBC 驅動名及數據庫 URL
    static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/ewqq?useSSL=false&serverTimezone=UTC&useLocalSessionState=true&rewriteBatchedStatements=true";
// 
 
    // 數據庫的用戶名與密碼,需要根據自己的設置
    static final String USER = "root";
    static final String PASS = "root";
    static String sql = "INSERT INTO `pi_liang_insert`(Ittest) VALUES ( ?)";
 
    public static void main(String[] args) {
        Connection con = null;
        try {
            con = DriverManager.getConnection(DB_URL,USER,PASS);
 
            PreparedStatement preparedStatement = con.prepareStatement(sql);
 
            con.setAutoCommit(false);
            long startTime = System.currentTimeMillis();
            System.out.println("開始……");
//            for (int i=0;i<100000;i++)
//            {
//                preparedStatement.setString(1,"asfsdfsdf"+i);
//                preparedStatement.addBatch();
//            }
//            preparedStatement.executeBatch();
            for (int j=0;j<1;j++)//防止最大命令字符數溢出
            {
                for (int i=0;i<1;i++)
                {
                    preparedStatement.setString(1,"It'test"+(i+j*10000));
                    preparedStatement.addBatch();
                }
                preparedStatement.executeBatch();
            }
        	System.out.println("preparedStatement"+preparedStatement.toString());
    		StringBuffer sqlBuffer = new StringBuffer();
    		sqlBuffer.append("INSERT INTO ").append("pi_liang_insert").append("(");
    		sqlBuffer.append("1");
    		sqlBuffer.append("2");
    		sqlBuffer.append("3");
    		sqlBuffer.deleteCharAt(sqlBuffer.length()-1);
    		System.out.println("sqlbuffer"+sqlBuffer.toString());
            long endTime  = System.currentTimeMillis();
            con.commit();
            System.out.println("用時:" + (endTime-startTime) + "毫秒");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        System.exit(0);
    }
 
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章