我在尝试将值插入数据库时遇到问题。
当我执行下面的代码时,它可以正常工作
insertString = "insert into Players
values(1,'Fred','Fish','fredfish@gamer.net','Ithroeann',19770322)";
statement.executeUpdate(insertString);
但是当我尝试这样做时,在这里它会给我一个不正确的语法' 0'错误
我试图将其循环以通过文件自动添加
Scanner input = new Scanner(new File("players.txt"));
while (input.hasNext()) {
String[] temp;
String str = input.next();
temp = str.split("\\|");
insertString = "insert into Players values(temp[0], temp[1],temp[2],temp[3],temp[4],temp[5])";
statement.executeUpdate(insertString);
}
答案 0 :(得分:1)
这是一个字符串。如果要将临时数组的元素附加到String,则不能这样做。
你可以这样做:
insertString = "insert into Players values("+temp[0]+",'"+temp[1]+"','"+temp[2]+"','"+temp[3]+"','"+temp[4]+"',"+temp[5]+")";
statement.executeUpdate(insertString);
当然使用PreparedStatement会是一个更好的解决方案。
PreparedStatement stmt = conn.prepareStatement("insert into Players values(?,?,?,?,?,?)");
stmt.setInt (1, Integer.parseInt(temp[0]));
stmt.setString (2, temp[1]);
stmt.setString (3, temp[2]);
stmt.setString (4, temp[3]);
stmt.setString (5, temp[4]);
stmt.setInt (6, Integer.parseInt(temp[5]));
stmt.executeUpdate();
答案 1 :(得分:1)
使用PreparedStatement
将查询参数绑定为
PreparedStatement pStmt = connection.prepareStatement(
"insert into Players values (?, ?, ?, ?, ?, ?)");
// index starts from 1
int i = 1;
// bind first int value
pStmt.setInt(i, Integer.parseInt(temp[0]));
// bind string values
for (; i < temp.length; i++)
pStmt.setString(i, temp[i-1]);
// bind last int value
pStmt.setInt(i, Integer.parseInt(temp[i-1]));
// execute insert
pStmt.executeUpdate();
答案 2 :(得分:0)
除非上面发布的代码是部分代码,否则您似乎错过了语句准备部分。尝试以下内容:
Scanner input = new Scanner(new File("players.txt"));
while (input.hasNext()) {
String[] temp;
String str = input.next();
temp = str.split("\\|");
dbConnection = getDBConnection(); // Implement this method based on your DB configuration
String insertString = "insert into Players values(?, ?, ? , ?, ?, ?)";
PreparedStatement statement = dbConnection.createStatement();
statement.setInt(temp[0]); // int, or whichever type you have
statement.setInt(temp[1]); // int, or whichever type you have
statement.setInt(temp[2]); // int, or whichever type you have
statement.setInt(temp[3]); // int, or whichever type you have
statement.setInt(temp[4]); // int, or whichever type you have
// ^ for the above, if all fields are the same - you can do this in a loop
statement.executeUpdate(insertTableSQL); // execute the insert