MySQLSyntaxErrorException:“字段列表”中存在未知列“arpit”

问题描述 投票:0回答:1

这个 JDBC 程序有什么错误:

package jdbc;

import java.sql.*;
import java.util.Scanner;

public class Table {

    public static void main(String[] args) {
        String name;
        int age;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter name and age: ");
        name = sc.nextLine();
        age = sc.nextInt();
        try{
            Connection con = DriverManager.getConnection("jdbc:mysql:" +
                                 "//localhost/demo","root","");
            Statement st = con.createStatement();
            //SQL Query to insert user input
            String sql = "insert into tab values(3,"+name+","+age+");";  
            //Execute INSERT
            st.executeUpdate(sql);
            //Dislplay table "tab"
            ResultSet rs = st.executeQuery("select * from tab");
            while(rs.next()){
                System.out.println(rs.getInt(1) + " " + rs.getString(2)"+
                                   " " " + rs.getInt(3));
            }
        } catch(Exception e){
            e.printStackTrace();
        }
    }
}

输出:

Enter name and age: 
arpit          //user input
18             //user input
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'arpit' in 'field list'
    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:422)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:400)
    at com.mysql.jdbc.Util.getInstance(Util.java:383)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:980)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3847)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3783)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2447)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2594)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2541)
    at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1604)
    at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1535)
    at jdbc.Table.main(Table.java:20)
java mysql jdbc prepared-statement sql-injection
1个回答
4
投票

输入的值无效。使用

PreparedStatement
设置查询中的值。在 sql 中使用应插入值的列名称。 MySQL默认会自动生成主键,所以你不需要使用它。最后,您也不需要指定
;
。执行语句时,它会自动添加结束字符。

//SQL Query to insert user input
String sql = "insert into tab(name, age) values(?,?)";  
Statement st = con.prepareStatement(sql);

st.setString(1, name);
st.setInt(2, age);

//Execute INSERT
st.executeUpdate();
© www.soinside.com 2019 - 2024. All rights reserved.