使用占位符的插入语句

……
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{
	……	
		类名.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)


慕粉3209284
浏览 7902回答 2
2回答

慕粉3209284

st = conn.prepareStatement(sql);  int num = st.executeUpdate(sql);改为 int num =st.executeUpdate();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java
MySQL