简体   繁体   中英

Java Prepared statements for PostgreSQL

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:

  1. Place all your SQL statements in resource files and load the appropriate resource at runtime
  2. Where the statement or logic structures differ (requiring different parameters, etc), write the logic for both databases and choose the correct path depending on the database you are using.

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,

  1. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM