【问题标题】:transfer all records from one database table to another database table将所有记录从一个数据库表转移到另一个数据库表
【发布时间】:2019-05-25 16:03:33
【问题描述】:

我在一个数据库表中有记录,我想将所有记录转移到另一个数据库的表中。

我目前的代码只能在同一个数据库的表之间传输。

 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 @scaisEdge

标签: java sql sqlite


【解决方案1】:

如果您使用的是 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 有多种方法来处理这些事情,这些事情可能对你有用,也可能对你不起作用,这取决于你的需要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多