You must download a separate DB API module for each database you need to access. For example, if you need access to the Oracle database and MySQL database, you must download the Oracle and MySQL database modules.
The DB API provides the minimum standards for working with the database, using Python's structure and syntax whenever possible. This API includes the following:
Verify that the MYSQLDB module is installed successfully:
#!/usr/bin/env python
Import MySQLdb
If it produces the following result, then it means that the MySQLdb module is not installed:
Traceback (most recent): File "test.py", line 3, Inimport mysqldbimporterror:no module named MySQLdb
Download MYSQLDB module, install command under Linux environment
$ gunzip mysql-python-1.2.2.tar.gz$ tar-xvf mysql-python-1.2.2.tar$ cd mysql-python-1.2.2$ python setup.py build$ python setup.py Install
* Note Root permissions Installation
Database connection:
Ensure the following before connecting to a MySQL database:
-
you have created a database testdb.
-
You have created an employee table in TestDB.
-
employee table has the following fields: first_name, last_name, age, SEX and INCOME.
-
"testuser" User ID and password test12 "settings are used to access TestDB.
-
python module MYSQLDB properly installed on your machine.
-
You've passed the MySQL tutorial
Example 1: Connecting TestDB
#!/usr/bin/env pythonimport mysqldb# Open Database connectiondb = MySQLdb.connect ("Llocalhost", "TestUser", "test12", " TESTDB ") #prepare a Cursor object using the cursor () Methodcursor = Db.cursor () # Execute SQL Query using execute () methodcursor . Execute ("Select VERSION ()") #Fetch a single row using Fetch () Methoddata = Cursor.fetchone () print "Database version:%s"% Data#disconnect from Serverdb.close ()
While running this script on my Linux machine, it produces the following results.
Database version:5.0.45
This article is from the "Missed Footsteps" blog, please be sure to keep this source http://xxmspace.blog.51cto.com/1056016/1754124
Connect MySQL database with Python