We all know the power of MySQL — one of the
most used open source databases and a challenge to proprietary products
of the genre. Python and PHP are well-known scripting languages. We
combine these two powers in this article. So fasten your seatbelts, and
enjoy the ride!
================================================
MySQLdb
driver. It’s built into versions later than 2.3. You can also download it from its SourceForge project page and install it with the following commands:# tar -xvf foldername.tar.gz
# cd path-to-extracted-folder
#python setup.py install
Note: I am using Ubuntu 10.04 32-bit on my laptop, with
Python 2.7 and PHP 5.3.2. So the data provided is with respect to this
configuration.
Accessing MySQL through DB-API using
MySQLdb
comprises the following steps:- Import the
MySQLdb
module. - Open the connection to the server.
- Run your queries.
- Close the connection.
mysqlpython.py
:
import
MySQLdb
#1
connection
=
MySQLdb.connect(host
=
"servername"
, user
=
"username"
, passwd
=
"password"
, db
=
"databasename"
)
#2
cur
=
connection.cursor()
#3
cur.execute(
"create table lfy(name varchar(40), author varchar(40))"
)
#4
cur.execute(
"insert into lfy values('Foss Bytes','LFY Team')"
)
#5
cur.execute(
"insert into lfy values('Connecting MySql','Ankur Aggarwal')"
)
cur.execute(
"select * from lfy"
)
#6
multiplerow
=
cur.fetchall()
#7
print
“Displaying
All
the Rows: “, multiplerow
print
multiplerow[
0
]
cur.execute(
"select * from lfy"
)
row
=
cur.fetchone()
#8
print
“Displaying the first row: “, row
print
"No of rows: "
, cur.rowcount
#9
cur.close()
#10
connection.close()
#11
Figure 1 below shows the output of the Python script.
Figure 1: Output of the Python script
A few notes with respect to the above code:- We imported the
MySQLdb
module to use the database API. - We connected to the MySQL server by calling the
MySQLdb connect()
function. The parameters required were the server name, MySQL username, MySQL password, and the database you want to use. - To retrieve query results, we created
cur
, an object of thecursor()
class, which will be responsible for execution and fetching. cur.execute()
executes the query to create a table namedlfy
.- We inserted values into the
lfy
table. - We retrieved all values in the
lfy
table through aSELECT
query. cur.fetchall()
will fetch all results of the query, and return them as a nested list.cur.fetchone()
will fetch one row at a time. You might wonder why we executed theSELECT
query again — becausefetchall()
has already fetched all results of the previous query, and callingfetchone()
would returnNone
.- The
rowcount
property tells us the number of rows returned by the query. - We closed the cursor object, freeing the resources it holds.
- We closed the connection. Always remember to close the connections; otherwise, it may be a major security risk.
Note: Python being an interpreted
language, it executes code line by line. If an error occurred on the 8th
line, by then, it has executed the first seven lines, creating the
table and inserting entries. The connection also remains open.
Therefore, I recommend you adopt error and exception handling while
using databases.
Connecting MySQL with PHP
PHP is very popular for server-side scripting, and MySQL databases are widely used for storage of the data used in dynamic pages. Connecting to MySQL from PHP is quite easy, with in-built functions; it follows the same four rules we discussed in the Python section. We will do the same basic tasks as the Python script; so before trying out the code below, drop the previous table. Here’s our PHP script,mysqlphp.php
:<?php
$connection
=mysql_connect(
"servername"
,
"username"
,
"password"
)
or
die
(
"connectivity failed"
); #1
mysql_select_db(
"database name"
,
$connection
); #2
$create
=
"create table lfy(name varchar(50), author varchar(50))"
;
mysql_query(
$create
,
$connection
); #3
$insert1
=
"insert into lfy values('Foss Bytes','LFY Team')"
;
$insert2
=
"insert into lfy values('Connection Mysql','Ankur Aggarwal')"
;
mysql_query(
$insert1
,
$connection
);
mysql_query(
$insert2
,
$connection
);
$fetch
= mysql_query(
"select * from lfy"
);
while
(
$row
=mysql_fetch_array(
$fetch
)) #4
{
print_r(
$row
); #5
}
mysql_close(
$connection
); #6
?>
A detailed explanation of the above script is given below:
- If the connection to MySQL fails, we use the
die()
function as an error-handling technique, to stop processing the page. The connection object is passed to other MySQL-related functions for use. - We selected the database we want to use.
- We used
mysql_query()
to execute queries. mysql_fetch_array()
will fetch the results of the query in the form of an array. We have used awhile
loop to display the results.- To display the data, we used
print_r()
, which will display the whole row at one go. To access individual fields, use a string index of the field-name, likerow["name"]
, etc. See the output screenshot (Figure 2) for a clearer understanding. - We closed the connection to the MySQL server.
No comments:
Post a Comment