提问人:Arpit Tomar 提问时间:7/5/2015 最后编辑:Roman CArpit Tomar 更新时间:9/10/2023 访问量:111
这个JDBC程序有什么错误
What's the mistake in this JDBC program
问:
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)
答:
4赞
Roman C
7/5/2015
#1
输入的值无效。用于设置查询中的值。在 sql 中使用应插入值的列名。主键在 MySQL 中默认是自动生成的,因此您无需使用它。最后,您也不需要指定 .当语句执行时,它会自动添加结束字符。PreparedStatement
;
//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();
评论
1赞
Roman C
9/8/2023
如果这个答案对你有帮助,那么你应该把它标记为接受。我在答案左边的复选框。此外,值得投票支持帮助您的答案,以帮助其他人选择正确的答案。
评论
insert into tab values(3, arpit, 18)
arpit