statement.executeQuery(sql)出错的一种排查方法

在IDE里调试程序总是在执行SQL语句时报错(ps:如何定位错误?),这是一件很头疼的事。

一种比较有效的方法是:

(1)调用printf等输出函数,得到SQL语句

eg:

String sql = "select * from suser where name='"+name+"' and password='"+psd+"';";
System.out.println(sql);//这一行多余,但可确定“真正的”SQL语句

select * from suser where name= 'admin' and password='123456';

(2)直接去数据库中执行该SQL语句验证正确性。

只要数据库中语句能正确执行,就可确保 statement.executeQuery(sql)这条语句没有错误,至少不是SQL语句不对造成的错误。

(3)示例:

String sql = "select * from user where name='"+name+"' and password='"+psd+"';";
ResultSet resultSet = statement.executeQuery(sql);

第二条语句在编译器(Idea)中报错,输出SQL语句为 select * from user where name= 'admin' and password='123456';

去SQLserver2012中执行,即使是简化的select * from user,也会报错。

百度得知,user是关键词不可出现在SQL语句中。

你可能感兴趣的:(问题+解决)