java - 我的 JAVA 程序中的 SQL 查询使用预处理语句完成,尽管正确,但抛出错误

标签 java mysql jdbc xampp

在我的java程序中,我尝试使用准备好的语句在MySQL表中进行插入操作。

这是我的 SQL 查询:

PreparedStatement stmt = null;

String sql="INSERT INTO registration"+"(phone,name,address,city,destination,date) VALUES"+ "(?,?,?,?,?,?)";

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...");
    stmt=conn.prepareStatement(sql);

    //STEP 4: Execute a query
    System.out.println("Inserting records into the table...");
   // stmt = conn.createStatement();
    stmt.setInt(1, phone[i]);
    stmt.setString(2, name[i]);
    stmt.setString(3, address[i]);
    stmt.setString(4, city[i]);
    stmt.setString(5, destination[i]);
    stmt.setString(6, date[i]);

    stmt.executeUpdate(sql);
}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;

我似乎在 SQL 查询中找不到任何错误,但程序抛出了语法错误。如果您需要,这是上下文的完整程序;

import java.util.*;
import java.sql.*;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

    public class Airplane {
        // JDBC driver name and database URL
        static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
        static final String DB_URL = "jdbc:mysql://localhost:3306/airplane";

        //  Database credentials
        static final String USER = "root";
        static final String PASS = "";

    public static void main(String args[])
    {   int i=0;int choice;
        Scanner sc=new Scanner(System.in);
        String name[]=new String[1000];
        String address[]=new String[1000];
        int phone[]=new int[1000];
        String city[]=new String[1000];
        String destination[]=new String[1000];
        String date[]=new String[1000];

        do {

            System.out.println("WELCOME TO AIRPLANE MANAGEMENT SYSTEM");
            System.out.println("Select your operation :");
            System.out.println("1:New Booking");
            System.out.println("2:List");
            System.out.println("3:Search");
            System.out.println("4:Edit");
            System.out.println("5:Delete");
            System.out.println("6:Bill");

            choice = sc.nextInt();
            switch (choice) {
                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;
                    PreparedStatement stmt = null;

                    String sql="INSERT INTO registration"+"(phone,name,address,city,destination,date) VALUES"+ "(?,?,?,?,?,?)";

                    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...");
                        stmt=conn.prepareStatement(sql);

                        //STEP 4: Execute a query
                        System.out.println("Inserting records into the table...");
                       // stmt = conn.createStatement();
                        stmt.setInt(1, phone[i]);
                        stmt.setString(2, name[i]);
                        stmt.setString(3, address[i]);
                        stmt.setString(4, city[i]);
                        stmt.setString(5, destination[i]);
                        stmt.setString(6, date[i]);

                        stmt.executeUpdate(sql);
                    }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;
                }


                case 2:
                    System.out.println("Name\tAddress\tContactNo\tPickUp City\tDestination\tDate");
                    for (int m = 0; m < i; m++) {
                        System.out.println(name[m] + "\t" + address[m] + "\t" + phone[m] + "\t" + city[m] + "\t\t" + destination[m] + "\t" + date[m]);

                    }
                    break;

                case 3:
                    System.out.println("enter the contact number to see details");
                    int search=sc.nextInt();
                    for (int m = 0; m < i; m++) {
                        if(search==phone[m])
                        System.out.println(name[m] + "\t" + address[m] + "\t" + phone[m] + "\t" + city[m] + "\t" + destination[m] + "\t" + date[m]);

                    }
                    break;
                case 4:
                    break;

                case 5:
                    break;
                case 6:
                    break;

            }
        }while(choice!=0);



    }//end main
    }//end JDBCExample

我做错了什么?

程序显示此错误:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?,?,?,?,?,?)' at line 1 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at com.mysql.jdbc.Util.handleNewInstance(Util.java:404) at com.mysql.jdbc.Util.getInstance(Util.java:387) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:942) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3966) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3902) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2526) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2673) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545) at com.mysql.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1540) at com.mysql.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2595) at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1468) at Airplane.main(Airplane.java:90)

最佳答案

您的问题似乎在这里:

stmt.executeUpdate(sql);

您已经向此处的语句提供了原始字符串查询:

stmt=conn.prepareStatement(sql);

executeUpdate()PreparedStatement 版本不带任何参数。看起来您正在访问由 PreparedStatement 继承的 Statement 接口(interface)中的版本,该接口(interface)运行作为参数传入的字符串。

我认为如果您从调用中删除 sql 字符串就会起​​作用:

stmt.executeUpdate();

关于java - 我的 JAVA 程序中的 SQL 查询使用预处理语句完成,尽管正确,但抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52884867/

相关文章:

mongodb - 如何配置 jndi Glassfish 4 连接到 mongoDB 数据库

java - Jersey 休息服务 + mySQL 数据库 : No suitable driver found

java - 如何向 Undertow 的 ClientRequest 添加 cookie?

java - 是否应该最小化 try catch 中的代码或管理它们的任何实践?

mysql - 执行语句只返回#Rows

php - 如何从 WordPress 数据库中选择帖子?

java - 有没有一种简单的方法可以在 java 中使用 ASCII 下降对 ArrayList<> 进行排序?

java - 如何使用java(套接字)连接/远程登录到SPOP3服务器?

mysql - 从同一个表中选择与逗号分隔值字符串匹配的所有行

java - Web界面如何从服务器获取数据?