perl连接mysql的实例代码

发布时间:2020-07-09编辑:脚本学堂
perl连接mysql的实例代码

perl连接mysql的实例代码,供大家学习参考。
 

复制代码 代码如下:
#!/usr/bin/perl
# load module
use DBI;

# connect
my $dbh = DBI->connect("DBI:mysql:database=db2;host=localhost", "joe", "guessme", {'RaiseError' => 1});

# execute INSERT query
my $rows = $dbh->do("INSERT INTO users (id, username, country) VALUES (4, 'jay', 'CZ')");
print "$rows row(s) affected ";

# execute SELECT query
my $sth = $dbh->prepare("SELECT username, country FROM users");
$sth->execute();

# iterate through resultset
# print values
while(my $ref = $sth->fetchrow_hashref()) {
print "User: $ref-> ";
print "Country: $ref-> ";
print "---------- ";
}

# clean up
$dbh->disconnect();