0

I have a sql query which when I manually sends to an Oracle DB through SQLDeveloper Application gets me the output I want. But the same query returns nothing while I try to connect and query through JDBC driver why this is happening so. Please help me.

code:

String sql = "select * from tablename where id='" + id + "' AND case_id = '" + case_id + "'";

stmt = con.createStatement();
rs = stmt.executeQuery(sql);
System.out.println(sql);
System.out.println("next = " + rs.next());

output:

select * from tablename where id='1' AND case_id = '1000'
next = false

Both connections (JDBC and SQLDeveloper) are using same username and password. So no issue of privilege or security i think.

4

1 回答 1

2

尝试将“id”作为数字传递。当您将 ID 作为字符串传递时,JDBC 驱动程序会将其转换为 CHAR、VARCHAR 或 LONGVARCHAR。

String sql = "select * from tablename where id=" + id + " AND case_id = '" + case_id + "'";

结果字符串:

select * from tablename where id=1 AND case_id = '1000'

考虑使用带有绑定参数的 PreparedStatement,以避免 sql 注入:

String sql = "select * from tablename where id = ? AND case_id = ?";

PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, 1);
ps.setString(2, "1000");

ResultSet rs = ps.executeQuery();

参考:

http://docs.oracle.com/javase/6/docs/technotes/guides/jdbc/getstart/mapping.html http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement .html

于 2013-05-28T04:15:27.647 回答