簡體   English   中英

使用Perl程序在MySQL的列中插入多行

[英]Inserting multiple rows in a column in MySQL using a Perl program

我想使用單個查詢在單個列中插入多行數據。 該程序用於減少數據。 我有另一個天氣監測.txt文件,有4000行數據。 我可以一次插入一個數據,但是對於這么多的數據值來說這很麻煩。

1.     use DBI;
2.     use DBD::mysql;
3.     use warnings;


4.     $connection = ConnectToMySql($database);

5.   # Multiple Data inputs
6.      $myquery = "INSERT INTO data(datatime,battery)
7.           VALUES
8.             (?,?),
9.             ('16.01.2013','6.54'), #data corresponding to date and battery
10.             ('17.01.2013','6.42'),
11.             ('21.01.2013','6.24'),
12.             ('22.01.2013','6.21'),
13.             ('24.01.2013','6.17'),
14.             ('25.01.2013','6.13'),
15.             ('28.01.2013','6.00'),
16.             ('29.01.2013','5.97'),
17.             ('30.01.2013','5.94'),
18.             ('01.02.2013','5.84')";
19.    $statement2 = $connection->prepare($myquery);

20.     $statement2->execute($myquery);

21.    #--- start sub-routine
22.    sub ConnectToMySql {
23.       $database ="xxxx";
24.       $user = "XXXX";
25.       $pass = "XXXX";
26.       $host="XXXX";
27.    my $dbh = DBI->connect("DBI:mysql:$database:$host", $user, $pass);
28.    }

此代碼給出了以下錯誤:

DBD :: mysql :: st執行失敗:您的SQL語法出錯; 檢查與您的MySQL服務器版本相對應的手冊,以便在C:/Users/User/workspace/DataBaseEntry/DataEntry.pl第20行的第2行''附近使用正確的語法。
DBD :: mysql :: st執行失敗:在C:/Users/User/workspace/DataBaseEntry/DataEntry.pl第40行需要2時,使用1個綁定變量調用。

我無法確定問題所在。 是占位符嗎? 我該怎么做才能改善它? 我是這些東西的新手。 所以你能保持簡單嗎? 謝謝

您應該傳遞應該替換(?, ?)作為參數的數據值來execute 您編寫的代碼只傳遞一個參數來execute ,該參數是查詢的SQL文本。

試試這個:

$myquery = "INSERT INTO data(datatime,battery) VALUES (?,?)";
my $sth = $connection->prepare($myquery);

$sth->execute('16.01.2013','6.54');
$sth->execute('17.01.2013','6.42');
$sth->execute('21.01.2013','6.24');
$sth->execute('22.01.2013','6.21');
$sth->execute('24.01.2013','6.17');
$sth->execute('25.01.2013','6.13');
$sth->execute('28.01.2013','6.00');
$sth->execute('29.01.2013','5.97');
$sth->execute('30.01.2013','5.94');
$sth->execute('01.02.2013','5.84');
$connection->do(<<'EOT');
  INSERT INTO data (datatime, battery)
  VALUES
    ('17.01.2013', '6.42'),
    ('21.01.2013', '6.24'),
    ('22.01.2013', '6.21'),
    ('24.01.2013', '6.17'),
    ('25.01.2013', '6.13'),
    ('28.01.2013', '6.00'),
    ('29.01.2013', '5.97'),
    ('30.01.2013', '5.94'),
    ('01.02.2013', '5.84')
EOT

我不確定你在這里嘗試使用占位符。

此外,您缺少use warnings; use strict; use warnings; use strict; ,你不應該在任何地方使用全局變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM