通过获取用户的输入,使用 java jdbc 在 MYSQL 中插入一行

Inserting a row in MYSQL using java jdbc by taking an input from user

我正在使用以下代码,但仍然出现错误

public void insertData(){  
String ch="y";
while(!"n".equals(ch)){
    Scanner sc=new Scanner(System.in);
    int i;
    String s;
    System.out.println("Enter new id");
    i=sc.nextInt();
    System.out.println("Enter new filename");
    s=sc.next();
    String sql = "INSERT INTO srt(id,file) " +
                   "VALUES (i, s)";
    try {
        st.executeUpdate(sql);
    } 
    catch (SQLException ex) {
        Logger.getLogger(Database_connect.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println("Do You wish to continue\n Enter 'n' to dis continue");
    ch=sc.next();
  }

}

错误如下:

Mar 04, 2015 12:10:58 PM database_connect.Database_connect insertData
SEVERE: null

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'i' in 'field list'

数据库中的列是 "id" 和 "file".id int(10),文件 varchar(100)

更改此声明:

 String sql = "INSERT INTO srt(id,file) " +
                   "VALUES (i, s)";

 String sql = "INSERT INTO srt(id,file) " +
               "VALUES ("+i+", '"+s+"')";

如果你使用你的语句,你有一个字符串而不是 sql 查询中变量的值。因此它尝试将列 i 和列 s 的值添加到 'idandfile`

但更好的方法是使用准备语句。

替换

String sql = "INSERT INTO srt(id,file) " + "VALUES (i, s)";

String sql = "INSERT INTO srt(id,file) " + "VALUES (" + i + ", " + s + ")";

您传递了字符串 i 和 s,正如您想传递变量 I 和 s 的值