You are on page 1of 4

Interacting with Database using MySQL

MySQLdb is an interface for connecting to a MySQL database server from Python. It


implements the Python Database API v2.0 and is built on top of the MySQL C API
Interacting with the Database
Most stored programs involve some kind of interaction with database tables. There are
four main types of interactions:
Store the results of a SQL statement that returns a single row into local variables.
Create a "cursor" that allows the stored program to iterate through the rows returned
by a SQL statement.
Execute a SQL statement, returning the result set(s) to the calling program.
Embed a SQL statement that does not return a result set, such as INSERT, UPDATE,
DELETE, etc.
The following sections look briefly at each type of interaction.
SELECTing INTO Local Variables
Use the SELECT INTO syntax when you are querying information from a single row of
data (whether retrieved from a single row, an aggregate of many rows, or a join of multiple
tables). In this case, you include an INTO clause "inside" the SELECT statement that tells
MySQL where to put the data retrieved by the query.
i. Connecting to the Database Server Using PHP
ii. Executing Queries using PHP and MySQL
For developing database driven web applications PHP is often used in conjunction with MySQL.
A few useful examples are provided here on using PHP
with MySQL. You require some basic knowledge of PHP for trying out these commands.
i. Connecting to Database
Two most commonly used functions to connect to the MySQL server are:.
1. mysql_connect()
2. mysql_select_db()
mysql_connect() function takes three arguments as localhost, username, password and
mysql_select_db() takes database name as argument.
These two functions are called by the following statements:
mysql_connect(localhost,username,password)
mysql_select_db(databasename)
mysql_connect function connects to the server and mysql_select_db() selects the database under
the username provided in mysql_connect()
function.
If any wrong name is given, the server responds with an error.

You can connect to MySQL server through PHP by using the above given hostname, username,
password by the way
mysql_connect('localhost','subu','subu')
mysql_select_db('sample_db')
This function selects the database sample_db.
Executing SQL
The mysql client typically is used interactively, like this:
shell> mysql db_name
However, it is also possible to put your SQL statements in a file and then tell mysql to read its
input from that file. To do so, create a text file text_file that contains the statements you wish to
execute. Then invoke mysql as shown here:
shell> mysql db_name < text_file
If you place a USE db_name statement as the first statement in the file, it is unnecessary to
specify the database name on the command line:
shell> mysql < text_file
If you are already running mysql, you can execute an SQL script file using the source command
or \. command:
mysql> source file_name
mysql> \. file_name
Sometimes you may want your script to display progress information to the user. For this you
can insert statements like this:
SELECT '<info_to_display>' AS ' '
The statement shown outputs <info_to_display>.
You can also invoke mysql with the verbose option, which causes each statement to be displayed
before the result that it produces. mysql ignores Unicode byte order mark (BOM) characters at
the beginning of input files. Previously, it read them and sent them to the server, resulting in a
syntax error. Presence of a BOM does not cause mysql to change its default character set. To do
that, invoke mysql with an option such as defaultcharacterset= utf8.
ii. Executing
There is a function in PHP called mysql_query(), by using which you can execute every MySQL
query which you are executing from command prompt.
Using the above table "student" you can do the following operation using PHP.
You can fetch records by executing:
$query="SELECT * FROM student"
$result=mysql_query($query)
or
$result=mysql_query("SELECT * FROM student")

The above function will return true if the query executed successfully else returns false, if query
is otherthan a SELECT statement.
If the query is a SELECT statement it returns result identifier.
You can test whether the query is ok on not as
if(!$result)
print(mysql_error())
else
print("Query OK")
mysql_error() is a function which returns the error in regard to the corresponding query.
There are four functions used for fetching data:
i. mysql_fetch_row :Returns row as an enumerated array.
ii. mysql_fetch_object :Returns row as an object.
iii. mysql_fetch_array :Returns as an associative array.
iv. mysql_result:Returns :One cell of data.
mysql_fetch_row() returns an array taking the above $result variable as argument
You can use this function to fetch the table data as:
while($data=mysql_fetch_row($result))
{
print("$data[0],$data[1],$data[2],$data[3]")
}
The function mysql_fetch_object performs the same task, except the row is returned as an object
rather than an array.
suppose $result=mysql_query("SELECTroll_no,name FROM student")
Then the procedure to get the value roll_no and name is:
while($row=mysql_fetch_object($result))
{
print("$row>
roll_no,$row>
name\n")
}
The most useful fetching function,mysql_fetch_array, offers the choice of results as an
associative array or enumerated array.
This means you can refer to outputs by database field name rather than number:
Example: use of mysql_fetch_array():
$query="SELECT roll_no,name ,specialization FROM student"
$result=mysql_query($query)
while($row=mysql_fetch_array($result))
{
print("$row[roll_no],$row[name],$row[specialization]")
}

Note:mysql_fetch_array can also be used with numerical identifiers rather than field names as in
mysql_fetch_row.
if you want to specify offset or field name rather than making both available , you can do it like
this:
$offset_row=mysql_fetch_array($result,MYSQL_NUM)
or
$associative_row =mysql_fetch_array($result,MYSQL_ASSOC)
mysql_result function is useful where you need only one piece of data.
An example of its usage:
$query="SELECT count(*) FROM student"
$result=mysql_query($query)
$data=mysql_result($result,0)
print("$data")
The mysql_result function takes two arguments: result identifier , row identifier. You can give
another one as an optional field
i.e. mysql_result($result,0,0)
Field can take the value of the field offset which is stored in variable $offset_row as given above.
You can execute INSERT, UPDATE, DELETE, ALTER statement as described above by putting
the query in mysql_query function

You might also like