【问题标题】:How to insert table into another database using perl?如何使用 perl 将表插入另一个数据库?
【发布时间】:2016-10-27 16:51:50
【问题描述】:

1.我有两个数据库(即database_1m和database_current)

2.我在 include_status 表中插入了一些列(即在 database_1m 中)。我想在 database_current 中插入相同的表。

3.每个数据库在 database_1m 中都有时间字段,我将获得所有时间,但在第二个数据库中,我只需要最近的时间行,所以我使用 mysql 查询获取最近更新的时间行(即 select * from include_status where time =(select max(time) from include_status);)

4.这里我不知道如何使用 perl 在同一个子程序中使用两个数据库? 代码:

sub data
{

    $DBH = &connect or die "Cannot connect to the sql server \n";
    $DBH->do("USE database_1m;");
    $stmt = "INSERT INTO include_status(time,available,closed,used,busy,reserved,down) VALUES(\"$current_time\",\"$include{'D'}\",\"$include{'B'}\",\"$include{'A'}\",\"$include{'C'}\",\"$include{'R'}\",\"$include{'+'}\")";


            my $sth = $DBH->prepare( $stmt );
            $sth->execute() or print "Could not insert data";
    $sth->finish;
    $DBH->disconnect();




}

Mysql查询:(插入最近更新的行)

 select * from include_status where time=(select max(time) from include_status);

【问题讨论】:

  • 我有点困惑。您想将表插入到不同的数据库中,还是将行插入到同一数据库的不同表中?我问是因为您提到“我想将相同的表从 database_1m 插入到 database_current”但代码显示 INSERT INTO include_status 告诉我 include_status 是表名?
  • 我想将同一张表插入另一个数据库(即databse_Current)。但是第二个数据库应该只包含最近更新的时间行。@user2082599
  • 如果该表不存在,则需要创建该表,然后通过从另一个表中选择插入到表中。 DBH 连接完全相同,但您只需添加 dbh2 作为连接名称,因为 dbh 已定义。
  • 但是如何在 $stmt 变量@user2082599 中插入 mysql 查询
  • 我现在将发布答案。

标签: perl dbi


【解决方案1】:

您需要“INSERT ... INTO ... SELECT ...”,它允许您运行选择查询并将结果直接插入另一个表。如果这两个表在同一台服务器上的不同数据库中,那么您应该可以直接在一个语句中完成。比如:

INSERT
INTO database_current.insert_status
SELECT *
FROM database_1m.insert_status
WHERE [some where clause]

我将重申我提出last time this code was posted 的一些观点。

  1. 请不要使用& 调用子例程。它会在某些时候让你感到困惑。请改用 connect()。
  2. 你没有用我的声明$DBH,这让我想知道你的代码中是否有use strict。您应该始终包含use strictuse warnings

【讨论】:

    【解决方案2】:

    插入将是这样的:

    my $stmt = "INSERT 
                INTO destination_table(time,available,closed,used,busy,reserved,down)
                SELECT time,available,closed,used,busy,reserved,down from original_table";
    

    【讨论】:

      猜你喜欢
      • 2015-03-31
      • 1970-01-01
      • 2018-03-13
      • 1970-01-01
      • 1970-01-01
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多