我想建立一個JDBC PreparedStatement,如:
SELECT URL,LOCATE ( '?', URL ) pos FROM Links WHERE pageId=? ORDER BY pos ASC
哪一号?是文字和第二?是一個參數.我可以使用CHAR(63)代替’?’但我認為額外的函數調用會減慢SQL執行速度.有沒有辦法逃脫第一次?
編輯:
下面的代碼測試dkatzel的斷言是什麼?字元串中的字元不被視為标記:
public class Test {
public static void main(String[] args) throws SQLException {
Connection conn = DriverManager.getConnection("jdbc:h2:mem:test");
Statement stmt = conn.createStatement();
stmt.executeUpdate("CREATE TABLE Links(URL VARCHAR(255) PRIMARY KEY,pageId BIGINT)");
stmt.executeUpdate("INSERT INTO Links(URL,pageId) VALUES('http://foo.bar?baz',1)");
stmt.executeUpdate("INSERT INTO Links(URL,pageId) VALUES('http://foo.bar/baz',1)");
stmt.close();
PreparedStatement ps = conn
.prepareStatement("SELECT URL,LOCATE ( '?', URL ) pos FROM Links WHERE pageId=? ORDER BY pos ASC");
ps.setLong(1, 1);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getString(1) + ":" + rs.getInt(2));
}
rs.close();
ps.close();
conn.close();
}
}
輸出:
http://foo.bar/baz:0
http://foo.bar?baz:15
似乎dkatzel是正确的.我搜尋了JDBC Spec并且找不到任何提及的那個?如果參數标記在引号内,則會被忽略,但我發現的少數PreparedStatement解析器實作(MySql,c-JDBC,H2)似乎都将單引号中的文本排除在考慮範圍内作為參數标記.