[英]insert query with varchar as data type for primary key
該程序不接受下面給出的查詢-
public class loginDaos {
public void create(loginBean bean) {
ConnectionPool c = ConnectionPool.getInstance();
c.initialize();
Connection con = c.getConnection();
try {
String sql = "INSERT INTO login VALUES(?,?,?,?)";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, bean.getCode());
pstmt.setString(2, bean.getUserid());
pstmt.setString(3, bean.getPassword());
pstmt.setString(4, bean.getPosition());
pstmt.executeUpdate(sql);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
loginDaos ld = new loginDaos();
loginBean lb = new loginBean("representative", "rep7", "rep7", "r");
ld.create(lb);
}
}
該表是:
CREATE TABLE login
( userid char(25);
password varchar(45),
code char(5),
position char(),
PRIMARY KEY (code)
);
我目前將userid,password,代碼和position的值保留為String。堆棧跟蹤為:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?,?,?,?)' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1936)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2060)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2536)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1564)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1485)
at login.loginDaos.create(loginDaos.java:33)
at login.loginDaos.main(loginDaos.java:42)
建立成功(總時間:0秒)
救命!
使用PreparedStatement
,應使用不帶String
參數的executeQuery()
, executeUpdate()
或execute()
方法。
因此,要解決此問題,請使用:
// ....
pstmt.setString(3, bean.getPassword());
pstmt.setString(4, bean.getPosition());
pstmt.executeUpdate();
MySQL驅動程序實現存在一個錯誤,因為JDBC規范指出,在PreparedStatement
或CallableStatement
實現上CallableStatement
時,接受字符串的方法應引發SQLException
。 在這種情況下,它僅引發異常,因為它嘗試直接執行參數化查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.