是否可以创建一个标准方法来使用 JDBC 执行从 Java 到 SQL Server 的参数化查询?
这是我创建数据库连接池的方法:
static ConnectionPool pool;
public static void crearPool(){
try {
Class c = Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Driver driver = (Driver) c.newInstance();
DriverManager.registerDriver(driver);
String url = "jdbc:sqlserver://localhost:1433;database=STAZIONE;";
pool = new ConnectionPool("local",5, 20, 40, 180, url, "b_lightyear", "BeyondInfinity");
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException ex) {/*Error Message*/}
}
我认为每个DML 查询的标准方法如下:
public static int QueryDML(String consulta,Object []data){
int result = 0;
PreparedStatement prpdStm = null;
try{
Connection cnx = pool.getConnection(clsConexion.espera);
if(conexion!=null){
prpdStm = conexion.prepareStatement(consulta,,ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
for(int position =1; position<data.length;position++){
prpdStm.setObject(position, data[position-1]);
}result = prpdStm.executeUpdate();
} else{/*Message*/}
} catch (SQLException ex) {/*Error Message*/}
return result;
}
我想知道的是 prpdStm.setObject(position, data[position-1]);
是否适用于任何类型的数据 ->(字符串
、整数
、 double
等...)?
最佳答案
What i want to know is if prpdStm.setObject(position, data[position-1]); will function for any type of data ->(String, Integer, Double, etc...)?
简短回答:是的。
根据 PreparedStatement.setObject()
JavaDoc 的答案稍长一些-
The JDBC specification specifies a standard mapping from Java Object types to SQL types. The given argument will be converted to the corresponding SQL type before being sent to the database.
关于java - 使用 JDBC 的参数化查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24878693/