我正在学习 Java JDBC,并使用循环将数据存储到数据库(mySQL db)中。 当我存储个人的名字和姓氏时,它似乎工作正常,但是当我尝试插入电子邮件地址时,出现以下错误:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,了解在“@123.com)”附近使用的正确语法
据我所知,除非我遗漏了一些非常明显的东西,否则我看不到我犯了什么语法错误?
我的代码如下:
import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
public class Driver {
public static void main(String[] args) {
try{
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:8889/demo","root","root");
Statement myStmt = myConn.createStatement();
ArrayList<String> firstNames = new ArrayList<String>(Arrays.asList("James", "John","Mark"));
ArrayList<String> lastNames = new ArrayList<String>(Arrays.asList("Handly", "licks","manford"));
ArrayList<String> emails = new ArrayList<String>(Arrays.asList("[email protected]", "[email protected]","[email protected]"));
for (int i = 0; i < firstNames.size(); i++){
String sql = "INSERT INTO EMPLOYEES (first_name,last_name,email) VALUES (" + firstNames.get(i)+ ", " + lastNames.get(i) + ", " + emails.get(i) + ");";
myStmt.executeUpdate(sql);
}
ResultSet myRes = myStmt.executeQuery("select * from Employees");
while(myRes.next()){
System.out.println(myRes.getString("first_name")+", "+ myRes.getString("last_name"));
}
}catch(Exception e){
e.printStackTrace();
}
}
}
当我尝试一次插入一个数据时
String sql = "INSERT INTO EMPLOYEES (first_name,last_name,email) VALUES ('John','test','[email protected]')";
myStmt.executeUpdate(sql);
工作正常,所以我很困惑为什么数据没有正确传递。 谢谢!
编辑: 感谢 @scaisEdge 和 @A.A 的反馈,虽然我正在寻找的修复确实有效,但使用字符串文字是一个BAD的想法,因为你打开了 SQL 注入。 反过来,我现在使用准备好的语句(@A.A的答案)修改了我的代码,这已经有效,并且问题少了很多!
新代码如下:
import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
public class Driver {
public static void main(String[] args) {
Connection myConn = null;
PreparedStatement myStmt = null;
ResultSet myRs = null;
try{
//1.get connection to db
myConn = DriverManager.getConnection("jdbc:mysql://localhost:8889/demo","root","root");
ArrayList<String> firstNames = new ArrayList<String>(Arrays.asList("James", "John","Mark"));
ArrayList<String> lastNames = new ArrayList<String>(Arrays.asList("Handly", "licks","manford"));
ArrayList<String> emails = new ArrayList<String>(Arrays.asList("[email protected]", "[email protected]","[email protected]"));
for (int i = 0; i < firstNames.size(); i++){
//Insert Query
myStmt = myConn.prepareStatement("INSERT INTO EMPLOYEES (first_name,last_name,email) VALUES (?,?,?)");
myStmt.setString(1,firstNames.get(i));
myStmt.setString(2,lastNames.get(i));
myStmt.setString(3,emails.get(i));
myStmt.execute();
}
ResultSet myRes = myStmt.executeQuery("select * from Employees");
while(myRes.next()){
System.out.println(myRes.getString("first_name")+", "+ myRes.getString("last_name"));
}
myConn.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
我还建议使用准备好的语句,它不仅更具可读性,而且还可以防止 SQL 注入攻击。更多信息这里
示例:
preparedStatement = connection.prepareStatement("INSERT INTO EMPLOYEES (fname, lname, email) VALUES (?, ?, ?)");
preparedStatement.setString(1, person.getFName());
preparedStatement.setString(2, person.getLName());
preparedStatement.setString(3, person.getEmail());
这更清楚,请注意addingAll中的虚拟参数,这是一个带有元素ElementOfAction的ArrayList - 不需要为不同的字段创建3个数组列表:
公共类 ElementOfAction {
String libelle;
Double montantUnit;
Integer quantityUnit;
}
public void addingAll(Connection connectDummy, ArrayList<ElementOfAction> arrayList){
DateAnalyses dateAnalyses = new DateAnalyses();
PreparedStatement smtPrepared;
ResultSet rs = null;
try {
Statement smt = connectDummy.createStatement();
/*sqlite> CREATE TABLE stock(
...> lib TEXT NOT NULL,
...> montant INTEGER,
...> quant INTEGER);
*/
smtPrepared = connectDummy.prepareStatement("INSERT INTO STOCK (lib,montant,quant) VALUES (?,?,?)");
int i =0;
do{
smtPrepared.setString(1,arrayList.get(i).getLibelle());
smtPrepared.setString(2, String.valueOf(arrayList.get(i).getMontantUnit())); /*second fiedls of j=1,...,n table database.db*/
smtPrepared.setString(3, dateAnalyses.returnStringByInteger(arrayList.get(i).getQuantityUnit())); /*thirdy fiedls of j=1,...,n table database.db*/
System.out.println(arrayList.get(i).getLibelle());
System.out.println(arrayList.get(i).getMontantUnit());
System.out.println(arrayList.get(i).getQuantityUnit());
i=i+1;
}while (i<arrayList.size());
rs = smt.executeQuery("SELECT * FROM STOCK");
/*
quantity = rs.getInt(2); */
/*second fiedls of j=1,...,n table database.db*//*
montant = rs.getInt(3); */
/*thirdy fiedls of j=1,...,n table database.db*/
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
维马纳斯印巴51区的外星技术: