为PostgreSQL编写的Java语句
我想为Oracle和PostgreSQL这两个数据库创建一个简单的应用程序。有没有办法对所有数据库使用一个Java代码?我试过这个:为PostgreSQL编写的Java语句,java,postgresql,Java,Postgresql,我想为Oracle和PostgreSQL这两个数据库创建一个简单的应用程序。有没有办法对所有数据库使用一个Java代码?我试过这个: public String init() { String user_name = null; try { Context ctx = new InitialContext(); if (ctx == null) throw new Exception("Boom - No Conte
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;
}
如何将准备好的语句用于此代码?这是一个非常广泛的问题,但多数据库兼容性的常用方法有两个:
code
中使用PreparedStatement
String selectSQL = "select id, user_name from user where username = ?"
PreparedStatement preparedStatement = dbConnection.prepareStatement(selectSQL);
preparedStatement.setString(1, "userName");
ResultSet rs = preparedStatement.executeQuery(selectSQL);
那么,到目前为止你试过什么?您应该能够使用SQL of
从user where username=?
中选择id、user\u name,然后适当地准备语句,设置参数并执行。现在还不清楚您的困难到底是在使用预先准备好的语句,还是在可移植性方面。请你澄清一下好吗?(您的数据库中真的有user\u name
和username
列吗?)。