当前位置: 代码迷 >> Java Web开发 >> 使用ps.setString()无效的有关问题,向插入一条记录
  详细解决方案

使用ps.setString()无效的有关问题,向插入一条记录

热度:7537   发布时间:2013-02-25 21:10:58.0
使用ps.setString()无效的问题,向插入一条记录
public boolean createTestPaper(TestPaper testPaper) {
//SQLUtil sqlUtil = new SQLUtil();
boolean showMessage = false;
String tId = testPaper.getTeacher().getUserId();
String id = testPaper.getId();
String sql = "insert into t_papers(teacher_id,id,name) values('"+tId+"','"+id+"',?)";
//sqlUtil.dealSQLPrint(sql);
Connection conn = null;
PreparedStatement ps = null;
conn = DBUtils.getConnection();
try {
boolean isCommited = conn.getAutoCommit();
conn.setAutoCommit(false);
ps = conn.prepareStatement(sql);
ps.setString(1, "name");

//执行到下面这句的时候报错(上面的数据都没有问题):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

int rs = ps.executeUpdate(sql);
if (rs == 1) {
showMessage = true;
conn.commit();
} else {
conn.rollback();
}
conn.setAutoCommit(isCommited);
} catch (SQLException e) {
System.out.println("errorSql:"+ps.toString());
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
System.out.println("回滚事务失败!");
}
e.printStackTrace();
} finally {
DBUtils.closeConnection(conn, ps, null);
}
return showMessage;
}


我尝试着输出ps.toString();这样得到了设置参数之后的sql语句 ,把这条语句直接复制到mysql中能够插入,但是在程序中就报错

------解决方案--------------------------------------------------------
楼主你的代码有点怪啊,你既然后面用到占位符?为什么前面2个id要去拼字符串了,你全部用占位符看看