I want to create simple application for 2 databases - Oracle and PostgreSQL. Is there any way to use one Java code for all databases? I tried this:
public String init()
{
String user_name = null;
try
{
Context ctx = new InitialContext();
if (ctx == null)
throw new Exception("Boom - No Context");
DataSource ds = (DataSource) ctx.lookup("jdbc/DefaultDB");
if (ds != null)
{
Connection conn = ds.getConnection();
if (conn != null)
{
Statement stmt = conn.createStatement();
ResultSet rst = stmt.executeQuery("select id, user_name from user where username = " + user);
if (rst.next())
{
user_name = rst.getString("user_name");
}
conn.close();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return user_name;
}
How I can use prepared statements with this code?
This is a very broad question, but the usual approach to multi-database compatibility is twofold:
Some database abstraction layers (Hibernate, Spring JDBC) can help with a lot of the work, but you will still need to be very aware of the differences and code for them.
You can work with more than one-database by single java-Code, but following way,
- Per Database separate Connection needs to be set-up
and you can use PreparedStatement
into your code
likewise,
String selectSQL = "select id, user_name from user where username = ?"
PreparedStatement preparedStatement = dbConnection.prepareStatement(selectSQL);
preparedStatement.setString(1, "userName");
ResultSet rs = preparedStatement.executeQuery(selectSQL);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.