【发布时间】:2014-07-25 13:56:36
【问题描述】:
考虑这种情况:在开发期间,我想使用MySQL,而在生产中我将使用derby。
要获得连接,我有这个来自java tutorial 的方法:
public Connection getConnection() throws SQLException {
Connection conn = null;
Properties connectionProps = new Properties();
connectionProps.put("user", this.userName);
connectionProps.put("password", this.password);
if (this.dbms.equals("mysql")) {
conn = DriverManager.getConnection(
"jdbc:" + this.dbms + "://" +
this.serverName +
":" + this.portNumber + "/",
connectionProps);
} else if (this.dbms.equals("derby")) {
conn = DriverManager.getConnection(
"jdbc:" + this.dbms + ":" +
this.dbName +
";create=true",
connectionProps);
}
System.out.println("Connected to database");
return conn;
}
这里还有一些涉及查询数据库 (again from java tutorial) 的代码:
public static void viewTable(Connection con, String dbName)
throws SQLException {
Statement stmt = null;
String query = "select COF_NAME, SUP_ID, PRICE, " +
"SALES, TOTAL " +
"from " + dbName + ".COFFEES";
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");
System.out.println(coffeeName + "\t" + supplierID +
"\t" + price + "\t" + sales +
"\t" + total);
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
if (stmt != null) { stmt.close(); }
}
}
我想知道是否需要根据我在后端使用的数据库来更改查询结构。
例如,MySQL 和 PostgreSql 似乎在查询中有一些 key differences。 (在上面的例子中它可能没有任何区别)。
我有 django 框架背景,其中ORM 旨在处理任何类型的数据库。相同的代码适用于任何插入的数据库。
【问题讨论】:
-
我认为这里的主要误解是 JDBC 不是 ORM。它只是抽象数据库访问,而不是查询它。为此,您需要一个“更高级别”的抽象,例如 JPA/Hibernate,它允许您使用 JPQL 等伪 SQL 语言编写独立于数据库的查询。
-
@mabi:感谢您的评论,有道理,思路清晰
标签: java mysql postgresql jdbc