……
public static void insert(String name,String password) throws Exception{
Connection conn = null;
PreparedStatement st = null;
ResultSet rs =null;
conn = DbUtils.getConn();
String sql="insert into User(name,password) values(?,?)";
st = conn.prepareStatement(sql);
st.setString(1,name);
st.setString(2, password);
int num = st.executeUpdate(sql);
if(num>0){
System.out.println("插入成功!!");
}
DbUtils.release(conn, st, rs);
}
public static void main(String args[]) throws Exception{
……
IUserDao.insert("hello","89790");
……
}
}
+----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| userID | int(11) | YES | | NULL | |
| name | varchar(255) | YES | | NULL | |
| sex | varchar(255) | YES | | NULL | |
| birthday | date | YES | | NULL | |
| password | varchar(255) | YES | | NULL | |
+----------+--------------+------+-----+---------+-------+
一直報錯,但是不知道是怎麼錯了。求教 orz
Exception in thread "main" 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:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.Util.getInstance(Util.java:387)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:939)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3878)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3814)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2478)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2625)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2547)
at com.mysql.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1541)
at com.mysql.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2605)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1469)
at dao.IUserDao.insert(IUserDao.java:107)
at dao.IUserDao.main(IUserDao.java:120)
表名沒錯,id不是自增的,沒有primarykey。把sql寫死是可以插入的,用“?”就不行了,為什麼呢?
看看錯誤信息:
【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】
sql的語法錯誤了
st = conn.prepareStatement(sql);
這個已經將sql語句設置了
st.setString(1,name);
st.setString(2, password);
** int num = st.executeUpdate(sql);**
你這裡就不要這個sql的參數了,不然認為你是按照sql中有值的方式不是占位符的方式來執行
int num = st.executeUpdate(sql);
改為
int num = st.executeUpdate();