我有一个 DAO 层可以像这样插入到 DERBY 数据库中,
try {
long id = dbAccess.insert(connection,
"INSERT INTO BOOKS(NAME, AUTHORS, PUBLISHYEAR, AVAIL) VALUES (?, ?, ?, ?)",
new ScalarHandler<BigDecimal>(),
book.getName(),
book.getAuthors(),
book.getPublishedYear(),
book.isAvailable()
).longValue();
return id;
} catch (Exception e) {
e.printStackTrace();
}
return -1L;
如果我使用 ORACLE DB 作为数据源,我该如何转换它?
我对您的数据库一无所知,但您需要定义插入表 ID 的方法,并且需要为您的 oracle 数据库创建连接类
你还需要管理你的表id增量你应该创建一个触发器来在每次插入操作后增加表id
我将发布一个从表中选择最大 ID 的方法,您可以在下面的链接中找到增加序列的 Oracle 触发器
How to create id with AUTO_INCREMENT on Oracle?
首先我们需要创建从您的表中返回最大 id 的方法
public static int getMaxBookID(Connection connection){
int id=0;
String sql = "SELECT NVL(MAX(ID),0)+1 FROM BOOK ";
try{
PreparedStatement statement = connection.prepareStatement(sql);
if(statement!=null){
try{
ResultSet results = statement.executeQuery();
if(results != null){
try{
if(results.next()){
id = results.getInt(1);
}
}
catch(Exception resultSetException) {resultSetException.printStackTrace();
}
results.close();
}
}
catch(Exception statmentExcption){statmentExcption.printStackTrace();
}
statement.close();
}
} catch (Exception generalException){generalException.printStackTrace();
}
return id;
}
这两个方法用于打开和关闭你的连接
private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
private static final String DB_CONNECTION = "jdbc:oracle:thin:@//host:1526/databasename";
private static final String DB_USER = "username";
private static final String DB_PASSWORD = "passowrd";
public static Connection lockConnection() {
Connection dbConnection = null;
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
return DriverManager.getConnection(
DB_CONNECTION, DB_USER, DB_PASSWORD);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
public static void closeMyConnection(Connection connection) {
try {
connection.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
现在您可以将您的信息插入到您的表中
public int AddBook(String name,String auth,String year , String avail){
int id=0;
Connection connection = lockConnection();
boolean ok = false;
String sql = "INSERT INTO BOOKS(ID,NAME, AUTHORS, PUBLISHYEAR, AVAIL)"
+ " VALUES(?,?,?,?,?)";
try{
PreparedStatement statement = connection.prepareStatement(sql);
if(statement!=null){
statement.setInt(1,getMaxBookID(connection));
statement.setString(2,name);
statement.setString(3,auther);
statement.setString(4,year);
statement.setString(5,avail);
try{
int count = statement.executeUpdate();
ok = count == 1;
if(!ok)id=0;
}
catch(Exception statmentExcption){statmentExcption.printStackTrace();statmentExcption.printStackTrace(); return 0 ;
}
statement.close();
}
} catch (Exception generalException){generalException.printStackTrace(); generalException.printStackTrace(); return 0;
}
closeMyConnection(connection);
return id;
}