Perl Database Connection Guide
In Perl, establishing database connections and operations usually involve using the DBI (Database Interface) module. Here is a simple example:
use DBI;
my $db_name = "database_name";
my $db_user = "username";
my $db_pass = "password";
my $dsn = "DBI:mysql:$db_name";
my $dbh = DBI->connect($dsn, $db_user, $db_pass) or die "Cannot connect to database: $DBI::errstr";
# 执行SQL查询
my $sql = "SELECT * FROM table_name";
my $sth = $dbh->prepare($sql);
$sth->execute();
# 获取查询结果
while (my @row = $sth->fetchrow_array()) {
print join(", ", @row) . "\n";
}
# 关闭数据库连接
$sth->finish();
$dbh->disconnect();
In the example above, we start by establishing a database connection using the DBI module, then we execute a simple SQL query and print the results of the query. Finally, we close the database connection. You can modify the database connection information and SQL query statement as needed.