使用DBUtils连接Sqlserver插入失败的问题
帅宏军
一、问题描述:
使用DBUtils对数据库Sqlserver进行插入操作时,失败,提示参数“?”不可识别。代码如下
- public void insert(Customer customer) {
- String sql = "insert into customer values(?,?,?,?,?,?,?,?,?)";
- Object[] args = { CustomerUtils.getID(), customer.getName(),
- customer.getGender(), customer.getBirthday(),
- customer.getCellphone(), customer.getEmail(),
- customer.getPreference(), customer.getType(),
- customer.getDescription() };
- // 在执行这段代码时就出错了
- QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
- try {
- queryRunner.update(sql, args);
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
public void insert(Customer customer) {
String sql = "insert into customer values(?,?,?,?,?,?,?,?,?)";
Object[] args = { CustomerUtils.getID(), customer.getName(),
customer.getGender(), customer.getBirthday(),
customer.getCellphone(), customer.getEmail(),
customer.getPreference(), customer.getType(),
customer.getDescription() };
// 在执行这段代码时就出错了
QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
try {
queryRunner.update(sql, args);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
问题原因发现是sqlserver的jdbc驱动在判断占位符类型的时候有问题;具体的就是获得ParameterMetaData的时候出了问题,这个时候可以用一个knowParaType的参数避免这个问题,就是在创建 QueryRunner的时候,提供一个true参数。
附上代码
- public void insert(Customer customer) {
- String sql = "insert into customer values(?,?,?,?,?,?,?,?,?)";
- Object[] args = { CustomerUtils.getID(), customer.getName(),
- customer.getGender(), customer.getBirthday(),
- customer.getCellphone(), customer.getEmail(),
- customer.getPreference(), customer.getType(),
- customer.getDescription() };
- //关键是这句加一个参数true
- QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource(),
- true);
- try {
- queryRunner.update(sql, args);
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
public void insert(Customer customer) {
String sql = "insert into customer values(?,?,?,?,?,?,?,?,?)";
Object[] args = { CustomerUtils.getID(), customer.getName(),
customer.getGender(), customer.getBirthday(),
customer.getCellphone(), customer.getEmail(),
customer.getPreference(), customer.getType(),
customer.getDescription() };
//关键是这句加一个参数true
QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource(),
true);
try {
queryRunner.update(sql, args);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
转载请注明出处:http://blog.csdn.net/shuaihj/article/details/15378109