我目前正在编写一个 CRUD 程序,我正在使用 hsql-db:
这是我的 hsql-db 连接器类:
public class hsqlmanager {
private static final Logger log = Logger.getLogger(hsqlmanager.class);
private static Connection con=null;
private static void openConnection(){
try {
Class.forName("org.hsqldb.jdbcDriver" );
log.info("Loaded JDBC Driver");
}
catch (Exception e) {
log.error("ERROR: failed to load JDBC driver - " + e.getMessage());
return;
}
try {
con = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/db_test","SA","");
log.info("Connection established");
}
catch(SQLException e){
log.error("db connection error Exception: " + e.getMessage());
}
}
public static void closeConnection() {
try {
con.close();
log.info("DB conn closed");
}
catch(SQLException e) {
log.error("Error at closing" + e.getMessage());
}
}
public static Connection getConnection() {
if (con==null){
openConnection();
}
else {
try {
if(con.isClosed()){
con = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/db_test","SA","");
log.info("DB connection re-opened.");
}
} catch(SQLException e){
log.error("re-open mistake" + e.getMessage());
return null;
}
}
return con;
}
}
这是我的crud类:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.apache.log4j.Logger;
public class DAOProdukt implements IDAOProdukt {
private static final Logger log = Logger.getLogger(DAOProdukt.class);
Connection conn;
public DAOProdukt(){
conn = hsqlmanager.getConnection();
}
//created ein Produkt p
@Override
public void create(Produkt p) {
if(p==null) { throw new IllegalArgumentException("Erstellen von null-Objekten in der DB nicht möglich");
}
PreparedStatement ps=null;
try {
ps = conn.prepareStatement("INSERT INTO Produkt(name, kategorie, delete) VALUES(?, ?, ?, ?);");
} catch (SQLException e1) {
log.error("Cannot establish db connection");
e1.printStackTrace();
}
try {
ps.setString(1, p.getName());
ps.setString(2, p.getKategorie());
ps.setBoolean(3, p.isDeleted());
ps.execute();
ps.close();
log.info("Produkt created.");
}
catch (SQLException e) {
log.error("Produkt couldn`t be created: " + e.toString());
}
}
}
编译器总是指向 crud 类并给我错误信息:
log.error("Cannot establish db connection");
非常感谢你的回答!!!
PS.:我使用该命令运行服务器: java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0 file:hsqldb/hemrajdb --dbname.0 db_test