使用DBI

时间:2017-05-16 15:00:06

标签: mysql perl dbi

我正在尝试连接到MySQL数据库。

我找到了这个脚本,我试图在我的PC和网络主机上使用它,但它没有显示任何输出。

请查看此代码。我在xampp上运行perl。

#!C:\xampp\perl\bin\perl.exe

print "Content-type: text/html\n\n";

use DBI;
use strict;

my $driver   = "localhost"; 
my $database = "data";
my $dsn      = "DBI:$driver:database = $database";
my $userid   = "root";
my $password = "";

my $dbh = DBI->connect($dsn, $userid, $password ) or die $DBI::errstr;

我在PHP中使用相同的数据库。

3 个答案:

答案 0 :(得分:3)

  

但它没有显示任何输出。

根据您正在显示的CGI标题判断,我假设您将其作为CGI程序运行。在这种情况下,您没有看到任何输出并不奇怪 - 您没有发送任何输出。

如果你将它作为一个命令行程序运行(并且在跳转到CGI编程之前让它在命令行上工作通常是一个好主意),那么你会看到" Content-Type& #34;头。或者,您可以向程序添加一些输出,看看它是否出现在您的浏览器中。简单的事情:

print 'It works!';

我还想补充一点,CGI看起来已经过时了,而且用Perl编写Web应用程序的方法要好得多(我的意思是更简单,更强大)。您可能希望阅读CGI::Alternatives以了解可用的内容。

更新:

我刚刚在Facebook上看到过这个问题(请不要在不告诉别人的情况下交叉发帖)并且我注意到你的$driver变量是错误的。如果您要连接到MySQL,那么$driver应该是" mysql" (以便DBI加载" DBD :: mysql")。

答案 1 :(得分:3)

MySQL驱动程序的DSN如下所示

port

databaseDBI:localhost:database = data 字段是可选的。 (my $dsn = "DBI:mysql:database=$database;host=$driver" 也是可选的,但你不想将其排除在外。)还有一些更深奥的选项,但它们在这里无关紧要

但是你正在提供

;host=$driver

哪个甚至没有指定MySQL连接,所以如果它不起作用我也不会感到惊讶!我不知道这些空间是否合法,但我会将它们留下来与文件保持一致。

您应该将该声明更改为

localhost

如果您愿意,可以删除my $dsn = "DBI:mysql:$database" (为什么要调用主机名"驱动程序"?),因为print是默认设置。仅指定数据库名称并使用所有其他字段的默认值的DSN可以简化为

text/plain

首先编写text/html语句可能更容易生成一些输出。您需要打印print "$DBI::errstr\n"而不是die的MIME内容类型标头。现在尝试import openpyxl wb = openpyxl.load_workbook('filename.xlsx') #getting the address address = list(wb.defined_names['metrics'].destinations) #removing the $ from the address for sheetname, cellAddress in address: cellAddress = cellAddress.replace('$','') #looping through each cell address, extracting it from the tuple and printing it out worksheet = wb[sheetname] for i in range(0,len(worksheet[cellAddress])): for item in worksheet[cellAddress][i]: print item.value` 代替{{1}},因为后者会写入不会出现在浏览器中的stderr

答案 2 :(得分:-1)

你可以添加:

if ($dbh) {
 print 'connect ok';
} else {
 print 'connect failed';
}
相关问题