简体   繁体   English

在Perl中运行多个SQL脚本

[英]Run multiple sql scripts in perl

I have 5 .sql scripts that create tables and insert into the tables. 我有5个.sql脚本来创建表并将其插入表中。 . I want to run them together as a transaction in PERL. 我想将它们作为事务在PERL中一起运行。 I have searched for it in Google and SO , but only I could find about running the scripts using Batch script. 我已经在Google和SO中进行了搜索,但是只有我能找到有关使用Batch脚本运行脚本的信息。 I have no idea how to run the scripts together using PERL DBI as a transaction . 我不知道如何使用PERL DBI作为事务一起运行脚本。 Can anyone please help. 谁能帮忙。 I am new to perl and mysql and I have no idea how to do that . 我是perl和mysql的新手,我不知道该怎么做。

This is what I am trying to do based on the suggestions by Barmar: 这是我根据Barmar的建议尝试做的事情:

#!/usr/bin/perl
use strict;
use warnings;
use DBI;
use Data::Dumper;

my $user="root";
my $password="M3m01r!@#";
my $db="DBI:$driver:database=$database";

my $dbh = DBI->connect("DBI:mysql:database=testdb;mysql_socket=/tmp/mysql.sock",$user,$password) or die "could not connect $DBI::errstr\n";
my $st = $dbh->prepare("mysql -u root -p < rr.sql") or die "$DBI::errstr\n";
$st->execute();

But it throws this error 但是它抛出了这个错误

DBD::mysql::st execute failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'mysql -u root -p < rr.sql' at line 1 at dbi.pl line 15.

Can anyone help please? 有人可以帮忙吗?

 ############################################################################
 my $st = $dbh->prepare("mysql -u root -p < rr.sql") or die "$DBI::errstr\n";
 ############################################################################

Line 2 is where you're broken. 第2行是您受伤的地方。

The string that you feed to prepare is supposed to be the actual SQL. 您准备要提供的字符串应该是实际的SQL。 You've fed it a shell command intended to run mysql. 您已经为它提供了一个用于运行mysql的shell命令。 So take the contents of rr.sql, put it in a variable (either have your program read it in, or copy/paste it), and then call prepare() on the variable. 因此,将rr.sql的内容放入一个变量中(让程序读取它,或将其复制/粘贴),然后对该变量调用prepare()。

 my $ferret_query = "select name, dob, type from ferret order by dob";
 my $sth = $dbh->prepare($ferret_query);
 $sth->execute()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM