java - 将所有记录从一个数据库表转移到另一个数据库表
问题描述
我在一个数据库表中有记录,我想将所有记录转移到另一个数据库中的表中。
我当前的代码只能在同一数据库中的表之间传输。
Statement st = conn.createStatement();
int rows = st.executeUpdate("Insert into script(ID,Name) Select ID,Name from table1");
if(rows==0){
JOptionPane.showMessageDialog(null,"Nothing to transfer.");
}else{
JOptionPane.showMessageDialog(null,rows+" transfered successfully into script");
}
}catch(SQLException | HeadlessException e){
JOptionPane.showMessageDialog(null,e);
}finally{
try{
rs.close();
pst.close();
}
catch(Exception e){
}
}
//and below are my database connections.
public into_databses(){
conn = connector.db1();
conn1 = connector.db2();
}
//and I am currently using only conn=connector.db1```
I want to modify it so that I can transfer records between tables in the different databases. thank you
解决方案
如果您使用的是 Sqlite3,则需要ATTACH DATABASE。
使用目标数据库连接,运行以下语句:
ATTACH DATABASE 'other.db' AS source;
INSERT INTO main.script(ID, Name) SELECT ID, Name FROM source.table1;
DETACH source; -- optional
other.db
您要从中复制的数据库的文件名在哪里。
处理重复主键等违反约束的事情留给读者作为练习 -INSERT
根据您的需要,有多种方法可以处理可能对您有用或可能不适合您的事情。
推荐阅读
- sapui5 - 如何在前端显示和下载从 sap ui5 中的 odata 字符串中提取的文件
- r - 如何将多张地图重叠成一张?
- ruby-on-rails - 如何修复错误 Bootsnap::LoadPathCache::FallbackScan: 当我运行 rails new app
- python-3.x - 如何同时使用不同 iframe 中的不同线程?
- acumatica - Acumatica - 将仪表板参数作为查询参数传递
- java - 在struts2项目的eclipse控制台上禁用无用的[freemark]日志
- c++ - 如何在不闪烁的情况下为 ESP32 运行单元测试?
- javascript - 单击路由不起作用,但在重新加载 URL 时它起作用
- dictionary - Deferencing 类型映射
- android-studio - Android Studio 3.5.1 中的软包装编辑器