Is it possible to create a standard method to execute parametrized queries from Java to SQL Server using JDBC?
Here's how i create a pool of connections to the db:
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*/}
}
And here's how i think a standard method for every DML Query would be:
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;
}
What i want to know is if prpdStm.setObject(position, data[position-1]);
will function for any type of data ->(String
, Integer
, Double
, etc...)?
What i want to know is if prpdStm.setObject(position, data[position-1]); will function for any type of data ->(String, Integer, Double, etc...)?
Short answer: Yes.
Slightly longer answer per the 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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments