这是我正在执行的 SQL 查询:
stmt = conn.createStatement();
String sql="INSERT INTO registration(phone,name,address,city,destination,date) VALUE ("+phone[i]+",'"+name[i]+"','"+address[i]+"','"+city[i]+"','"+destination[i]+"','"+date[i]+"')";
这是程序的相关部分,我在其中对 context 进行 SQL 查询。查询似乎是正确的。程序没有抛出任何错误,但数据没有插入到 MySQL 表中
case 1: {
System.out.println("Enter your Phone number:");
phone[i] = sc.nextInt();
sc.nextLine();
System.out.println("Enter your name:");
name[i] = sc.nextLine();
System.out.println("Enter your address:");
address[i] = sc.nextLine();
System.out.println("Enter your Pick up city:");
city[i] = sc.nextLine();
System.out.println("Enter your Destination:");
destination[i] = sc.nextLine();
System.out.println("Enter your Date:");
date[i] = sc.nextLine();
++i;
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Inserting records into the table...");
stmt = conn.createStatement();
String sql="INSERT INTO registration(phone,name,address,city,destination,date) VALUE ("+phone[i]+",'"+name[i]+"','"+address[i]+"','"+city[i]+"','"+destination[i]+"','"+date[i]+"')";
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
break;
}
程序没有抛出任何错误,但我的 MySQL 显示没有插入新条目。为什么会发生这种情况?
最佳答案
据我所知,您正在构造字符串sql
,但您没有在任何地方使用它。
以下代码用于执行查询:
stmt.executeUpdate(sql);
参见Oracle - Processing SQL Statements了解更多相关信息。
与您的问题无关,但是 Prepared Statements您可能也想研究一下,因为您正在将用户输入直接插入数据库。用户的输入也可能是恶意的,这里有更多解释W3Schools - SQL Injection
关于尽管没有显示错误,但 Java 数组元素未插入到 MySQL 表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52879318/