读书人

数据库更新出有关问题(上火啊)

发布时间: 2012-01-10 21:26:51 作者: rapoo

数据库更新出问题(上火啊)
代码如下,CON是数据库连接驱动类
public class testmain {
private static String user_id= "cc ";
private static String password= "ccc ";
private static String company_id= "asdfsa ";
private static String role_id= "sadfsdf ";
private static String car_no= "asdfasdf ";
private static String vehicle_team= "asdfasd ";
private static String user_name= "asdf ";
private static String certificate= "asdfsdf ";
private static String address= "asdfsdf ";
private static String addressnumber= "asdfafd ";
private static String call= "adsfsad ";
private static String email= "adfasfd ";

/** Creates a new instance of testmain */
public testmain() {
}
public static void main(String args[])
{
sql_con con=new sql_con();
int result=0;
try{
//下面这个更新执行错误~~~

String hello= "insert into gps_user values( ' "+
user_id+ " ', ' "+password+ " ', ' "+role_id+ " ' , ' "+company_id+ " ', "+car_no+ " ', ' "+vehicle_team+ " ', ' "+user_name+ " ', ' "+certificate+ " ', "+address+ " ', ' "+addressnumber+ " ', ' "+call+ " ', ' "+email+ " ') ";
result=con.sm.executeUpdate(hello);
//而下面这个更新执行却是正确的


/*String command= "insert into gps_user values( 'bbbbbb ', 'sdfsafd ', 'safsadf ', 'asdfsadf ', 'sadfsdf ', 'asdfasdf ', 'ggg ', 'bbb ', 'asdf ', '1sadfs ', '1asdf1 ', '000sdf ') ";
int result=con.sm.executeUpdate(command);*/


System.out.println(result);
}
catch(Exception e){
System.out.println(result);
}
finally{con.CloseConn();}
}
}
实在是搞不懂,这两个更新不是一样吗?

[解决办法]
"+car_no+ " '、 "+address+ " 前少了个单引号

为什么不用 PreparedStatement 的 ?占位符。看看那些单引号和加号,头晕了吧。

建议改成:

String sql= "insert into gps_user values(?,?,?,?,?,?,?,?,?,?,?,?) ";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, user_id);
ps.setString(2, password);
...
ps.setString(12, email);

int result = ps.executeUpdate();

读书人网 >J2SE开发

热点推荐