java-sql 与 绑定变量

除了通过存储过程便于实现绑定变量外,通过PreparedStatement 也可实现。

如下是绑定变量的方式:

public static void main(String args[]) throws SQLException,

ClassNotFoundException {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Class.forName("oracle.jdbc.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:oci8:@cc",
"hong", "hong");
String sql = "select * from emp where a=?";
PreparedStatement mysts = conn.prepareStatement(sql);
int kk = 1;
mysts.setInt(1, kk);
ResultSet rec = mysts.executeQuery();
while (rec.next()) {
System.out.println(rec.getString(2));
}

}

如下不是绑定变量的方式:

public static void bind(int i) throws Exception {
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
} catch (SQLException e) {
e.printStackTrace();
}
Class.forName("oracle.jdbc.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:oci8:@cc",
"hong", "hong");
Statement mysts = conn.createStatement();
ResultSet rec = mysts.executeQuery("select * from emp where a="+i);
while (rec.next()) {
System.out.println(rec.getString(2));
}
}

你可能感兴趣的:(10g,11g)