我正在尝试插入sql,但它一直给我错误

时间:2019-05-04 08:13:33

标签: java oracle jdbc

我想通过Java插入sql,但它给我错误

public void addStudent(String name, int SID, String gender, String major, String nationality, int mobileNo,
            String birthDate, int deptNo) {

        try {
            PreparedStatement stmt = conn.prepareStatement("insert into students values("+ SID+ ", '"+name+"','"
                    + gender+"',"+mobileNo + ",TO_Date('"+birthDate+"', 'DD/MM/YYYY'), '"+ major+"', '"+nationality+"', null, "+deptNo+");");
            stmt.execute();
        } catch (SQLException e) {

            e.printStackTrace();
            return;

        }
    }
  

java.sql.SQLSyntaxErrorException:ORA-00933:SQL命令不正确   结束

2 个答案:

答案 0 :(得分:1)

我不建议您这样使用PreparedStatement。 这就是我要做的:

public void addStudent(Student student){
      int SID = student.getSID();
      String name = student.getName();
      // etc ...

      String query = "INSERT INTO students VALUES(?,?)";

      try{

         PreparedStatement prep = conn.prepareStatement(query);
         prep.setInt(1,SID);
         prep.setString(2,name);
         // etc ...

         prep.executeUpdate();

      }catch (SQLException e){

            e.printStackTrace();

      }
}

答案 1 :(得分:1)

使用PreparedStatement如下:

       try {
         //passing placeholder 
            PreparedStatement stmt = conn.prepareStatement("insert into students values(?,?,?,?,?,?,?,?,?)");
          //giving valuesto each placeholder 
           stmt.setInt(1,SID);
            stmt.setString(2,name);
            stmt.setString(3,gender);
            stmt.setInt(4,mobileNo );
            stmt.setDate(5,birthDate);
            stmt.setString(6,major);
            stmt.setString(7,nationality);
            stmt.setString(8,null);
            stmt.setInt(9,deptNo ); 
            //executing update,insert value in table
            stmt.executeUpdate();
        } catch (SQLException e) {

            e.printStackTrace();
            return;

        }