Wednesday 9 October 2013

basic_perl_script_to_connect_mysql

This is a simple perl program to connect to mysql database and show the tables, and later how to run the same code in apache web server.

perl code:

#!/usr/bin/perl -w

use DBI;

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

## mysql user database name
$db ="mysql";
## mysql database user name
$user = "root";

## mysql database password
$pass = "yourPassword";

## user hostname : This should be "localhost" but it can be diffrent too
$host="localhost";

## SQL query
$query = "show tables";

$dbh = DBI->connect("DBI:mysql:$db:$host", $user, $pass);
$sqlQuery  = $dbh->prepare($query)
or die "Can't prepare $query: $dbh->errstr\n";

$sqlQuery->execute
#$rv = $sqlQuery->execute
or die "can't execute the query: $sqlQuery->errstr";

print "<h3>********** My Perl DBI Test ***************</h3>";
print "<p>Here is a list of tables in the MySQL database $db.</p>";
while (@row= $sqlQuery->fetchrow_array()) {
my $tables = $row[0];
print "$tables\n<br>";
}

#$rc = $sqlQuery->finish;
$sqlQuery->finish;
exit(0);



To run the same in the web:

# Lets say you have apache web server:

copy the same code at /usr/lib/cgi-bin directory with execution permission and then you can use [ http://localhost/cgi-bin/perlScript.pl ] at your web browser.

Make sure that your apache we server is running and the perl script is there at /usr/lib/cgi-bin directory with execution permission.




http://httpd.apache.org/docs/2.0/howto/cgi.html

For Python to connect to DB and other DB related example:

http://zetcode.com/db/mysqlpython/ 

Simple code to execute the code at web:
cat pythonHelloWorld.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-

# enable debugging
import cgitb
cgitb.enable()

print "Content-Type: text/plain;charset=utf-8"
print

print "Hello World!"
 


NOTE: Make sure, the script in executable permission and under the cgi-bin directory. 

 Script compare:

http://hyperpolyglot.org/scripting



 

No comments:

Post a Comment