通过获取用户的输入,使用JavaJDBC在MYSQL中插入一行
我正在使用下面的代码,但仍然得到错误通过获取用户的输入,使用JavaJDBC在MYSQL中插入一行,java,mysql,jdbc,insert,Java,Mysql,Jdbc,Insert,我正在使用下面的代码,但仍然得到错误 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 filena
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),file varchar(100)更改此语句:
String sql = "INSERT INTO srt(id,file) " +
"VALUES (i, s)";
到
如果使用语句,则在sql查询中有一个字符串,而不是变量的值。因此,它尝试将列i
和列s
的值添加到'id和
文件中`
但更好的方法是使用预先准备好的语句。替换
String sql = "INSERT INTO srt(id,file) " + "VALUES (i, s)";
与
您传递了字符串i和s,正如您希望传递变量i和s的值一样
String sql = "INSERT INTO srt(id,file) " + "VALUES (i, s)";
String sql = "INSERT INTO srt(id,file) " + "VALUES (" + i + ", " + s + ")";