在写sql语句的时候,总是报错,原来是’'单引号没有加
拼接语句的后半部分,之前仅仅是简单的""双引号拼接,报一些莫名其妙的错误,一直说sql语句有问题,但是看不出来,原来是’'单引号没有加.
完整代码
@Test
public void InsertDB() throws ClassNotFoundException, SQLException {
final String url = "jdbc:mysql://localhost:3306/day10?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false";
final String driverClassName = "com.mysql.jdbc.Driver";
final String username = "root";
final String password = "root";
Connection conn = null;
Class.forName(driverClassName);//指定连接类型
conn = DriverManager.getConnection(url, username, password);//获取连接
//sql前缀
String prefix = "insert into class10 (name,age,gender) values ";
//开始写后缀
Random random = new Random();
//设置事务非自动提交
conn.setAutoCommit(false);
Statement st = conn.createStatement();
for (int i = 0; i <10 ; i++) {
StringBuffer suffix = new StringBuffer();
//第一次提交步长
for (int j = 0; j <1000 ; j++) {
suffix.append("('"+"勾指起誓"+"','"+ "32"+"','"+"男"+"') ");
//完整sql语句
String sql = prefix + suffix;
st.executeUpdate(sql);
conn.commit();
suffix = new StringBuffer();
}
}
st.close();
conn.close();
}