java.sql.SQLException: 在 index:: 1 处缺少 IN 或 OUT 参数

2022-09-01 13:04:57

我做了一些Java 1.6-Oracle11g-JDBC(使用OJDBC 6)代码(如下)。我遇到异常 - 为什么会发生这种情况,我该如何解决?java.sql.SQLException: Missing IN or OUT parameter at index:: 1

我的输出是-

create CREATE TABLE employee(emp_name varchar(25),emp_address varchar(25))
insert INSERT INTO employee(jim,germany) values(?,?)
Exception: java.sql.SQLException: Missing IN or OUT parameter at index:: 1

代码是-

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;


public class Oracle {

public static void main(String[]args)
{

    try
    {

        Connection con = DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/xe", "newman", "123456");
        Statement stmt = con.createStatement(); 

        String create = "CREATE TABLE employee(emp_name varchar(25),emp_address varchar(25))";
        System.out.println("create " + create);//
        stmt.execute(create);

        //insert 1st row            
        String inserting = "INSERT INTO employee(hans,germany) values(?,?)";
        System.out.println("insert " + inserting);//
        PreparedStatement ps = con.prepareStatement(inserting); 
        ps.executeUpdate();

        //insert 2nd row            
        inserting = "INSERT INTO employee(david,austria) values(?,?)";
        System.out.println("insert " + inserting);//
        ps = con.prepareStatement(inserting); 
        ps.executeUpdate();

    }catch(SQLException ex){System.out.println("Exception: " + ex);}


    }

}

编辑 - 为了更正代码,我们使用 -

插入第一行

        String inserting = "INSERT INTO 
                    employee(emp_name,emp_address) values(?,?)";
        PreparedStatement ps = con.prepareStatement(inserting);
        System.out.println("insert " + inserting);//
        ps.setString(1, "hans");
        ps.setString(2, "germany");
        ps.executeUpdate();

插入第二行

        inserting = "INSERT INTO 
                    employee(emp_name,emp_address) values(?,?)";
        ps = con.prepareStatement(inserting);
        System.out.println("insert " + inserting);//
        ps.setString(1, "david");
        ps.setString(2, "austria"); 
        ps.executeUpdate();

答案 1

这不是 SQL 的工作方式:

INSERT INTO employee(hans,germany) values(?,?)

这些值应使用列名 。这些值由程序使用这些方法提供。这是抱怨,因为你说有两个参数(问号),但没有提供值。(hans,germany)(emp_name, emp_address)Statement.setString(pos,value)

您应该创建一个预准备语句,然后设置参数值,如下所示:

String insert= "INSERT INTO employee(emp_name,emp_address) values(?,?)";
PreparedStatement stmt = con.prepareStatement(insert);
stmt.setString(1,"hans");
stmt.setString(2,"germany");
stmt.execute();

答案 2

必须使用列名,然后设置要插入的值(两个 ? 标记):

//insert 1st row            
String inserting = "INSERT INTO employee(emp_name ,emp_address) values(?,?)";
System.out.println("insert " + inserting);//
PreparedStatement ps = con.prepareStatement(inserting); 
ps.setString(1, "hans");
ps.setString(2, "germany");
ps.executeUpdate();

推荐