Basic tutorial for Python operation MySQL

Source: Internet
Author: User

python operation MySQL

Recently learning Python, this scripting language is undoubtedly associated with databases, so here's how to use Python to manipulate MySQL databases. I Python is also 0 basic learning, so this blog is for beginners python, Daniel can choose to bypass.

In addition, this blog based on the environment is Ubuntu13.10, the use of the Python version is 2.7.5.

MySQL Database

MySQL is a world-leading open source database management system. It is a multi-user, multi-threaded database management system, and Apache, PHP, Linux together to form a lamp platform, widely used in Web applications, such as Wikipedia and YouTube. MySQL consists of two versions: Server system and Embedded system.

Environment Configuration

Before we start grammar learning, we also need to install MySQL and Python modules for MySQL operations.

Install MySQL:

sudo apt-get install mysql-server

During the installation, you will be prompted to enter the root account password, in accordance with the password specification.

Next, you need to install the Python operation module for MySQL:

sudo apt-get install python-mysqldb

Note: After installing PYTHON-MYSQLDB, we have installed two Python operating modules by default, namely the _mysql supporting the C language API and the MYSQLDB that support the Python API. We will focus on the use of the MySQLdb module later.

Next, we go into MySQL and create a test database called TestDB. The Create command is:

create database testdb;

We then create a test account to manipulate the TestDB database, creating and authorizing commands such as the following:

create user ‘testuser‘@‘‘ identified by ‘test123‘;grant all privileges on testdb.* to ‘testuser‘@‘‘;
_mysql Module

The _mysql module directly encapsulates the C language API function of MySQL, which is incompatible with the Python standard database API interface. I recommend that you use the object-oriented MYSQLDB module only to operate MySQL, here is only one example of using the _mysql module, this module is not the focus of our study, we just need to understand that the module is good.

#!/usr/bin/python#-*-Coding:utf-8-*-Import_mysqlImportSysTry: con = _mysql.connect (' ',' TestUser ',' test123 ',' TestDB ') Con.query ("Select VERSION ()") result = Con.use_result ()Print "MYSQL version:%s"% Result.fetch_row () [0]except_mysql. Error, E:Print "Error%d:%s%s"% (e.args[0], e.args[1]) Sys.exit (1)finally:ifCon:con.close ()

This code is mainly to get the current version of MySQL, you can simulate knocking this part of the code and then run it.


MYSQLDB is further encapsulated on the basis of the _mysql module and is compatible with the Python standard database API interface, which makes the code easier to migrate. Python also recommends using this MYSQLDB module for MySQL operations.

#!/usr/bin/python#-*-Coding:utf-8-*-ImportMySQLdb asMysqlTry: conn = Mysql.connect (' ',' TestUser ',' test123 ',' TestDB ') cur = conn.cursor () Cur.execute ("Select VERSION ()") Version = Cur.fetchone ()Print "Database version:%s"% versionexceptMysql. Error, E:Print "Error%d:%s"% (e.args[0], e.args[1]) exit (1)finally:ifConn:conn.close ()

We import the MySQLdb module and rename it to MySQL, and then call the MYSQLDB module's provided API method to manipulate the database. It is also the MySQL version number that gets the installation of the current host.

Create a new table

Next, we create a table from the MySQLdb module and populate it with some data. The implementation code is as follows:

#!/usr/bin/python#-*-Coding:utf-8-*-ImportMySQLdb asMysqlconn = Mysql.connect (' ',' TestUser ',' test123 ',' TestDB '); withConn:cur = Conn.cursor () Cur.execute ("DROP TABLE IF EXISTS Writers"); Cur.execute ("CREATE TABLE writers (id INT PRIMARY KEY auto_increment, name varchar)") Cur.execute ("INSERT into writers (name) values (' Wangzhengyi ')") Cur.execute ("INSERT into writers (name) values (' Bululu ')") Cur.execute ("INSERT into writers (name) values (' Chenshan ')")

The WITH statement is used here. The WITH statement executes the enter () and __exit () methods of the Conn object, saving itself from writing try/catch/finally.

When execution is complete, we can see whether the insert succeeds through the Mysql-client client, query statement:

select * from writers;

The query results are as follows:

ID name
1 Wangzhengyi
2 Bululu
3 Chenshan
Querying Data

We just inserted some data into the table, and then we took the inserted data from the tables with the following code:

#!/usr/bin/pythonimportas mysqlconn = mysql.connect(‘‘‘testuser‘‘test123‘‘testdb‘);with conn:    cursor = conn.cursor()    cursor.execute("select * from writers")    rows = cursor.fetchall()    forin rows:        print row

The query results are as follows:

(1L, ‘wangzhengyi‘)(2L, ‘bululu‘)(3L, ‘chenshan‘)
Dictionary cursor

We've just used the cursor either to create a database or to query the database. There are many types of cursor in the MYSQLDB module, and the default cursor is to return the data in the tuple's tuple form. When we use the dictionary cursor, the data is returned in the form of a Python dictionary. So we can get the query data by the column name.

Or the code that just queried the data, instead dictionary the cursor only needs to modify one line of code, as follows:

#!/usr/bin/pythonimportas mysqlconn = mysql.connect(‘‘‘testuser‘‘test123‘‘testdb‘);with conn:    cursor = conn.cursor(mysql.cursors.DictCursor)    cursor.execute("select * from writers")    rows = cursor.fetchall()    forin rows:        print"id is %s, name is %s" % (row[‘id‘], row[‘name‘])

Using the dictionary cursor, the query results are as follows:

idis1nameis wangzhengyiidis2nameis bululuidis3nameis chenshan

Students who have previously written PHP should be aware of precompilation, and precompiling can help us prevent web attacks such as SQL injection from also helping to improve performance. Of course, Python must also support precompilation. The precompiled implementation is also relatively simple to replace the real variables with placeholders such as%. For example, to query the information for a user with ID 3, use the precompiled code as follows:

#!/usr/bin/pythonimportas mysqlconn = mysql.connect(‘‘‘testuser‘‘test123‘‘testdb‘);with conn:    cursor = conn.cursor(mysql.cursors.DictCursor)    cursor.execute("select * from writers where id = %s""3")    rows = cursor.fetchone()    print"id is %d, name is %s" % (rows[‘id‘], rows[‘name‘])

I have used a placeholder for%s to replace "3", which represents a string type that needs to be passed in. If the incoming string is not of type, an error is run.


A transaction is an atomic operation of data in one or more databases. In one transaction, all the effects of the SQL statements are either committed to the database or all are rolled back.

For a database that supports transactional mechanisms, the Python interface begins a transaction when the cursor is created. You can commit all the changes through the cursor object's commit () method, or you can use the Rollback method of the cursor object to roll back all the changes.

I write a code here to insert the non-existent table, when the exception is thrown, call rollback to rollback, the implementation code is as follows:

#!/usr/bin/python#-*-Coding:utf-8-*-ImportMySQLdb asMysqlTry: conn = Mysql.connect (' ',' TestUser ',' test123 ',' TestDB '); cur = conn.cursor () Cur.execute ("INSERT into writers (name) values (' Wangzhengyi4 ')") Cur.execute ("INSERT into writers (name) values (' Bululu5 ')") Cur.execute ("INSERT into WRITERSS (name) VALUES (' Chenshan6 ')") Conn.commit ()exceptMysql. Error, E:ifConn:conn.rollback ()Print "Error happens, rollback is call"finally:ifConn:conn.close ()

The results of the implementation are as follows:

rollback is call

Because the first two data is the correct insert operation, but because of the overall rollback, so the database also does not have WANGZHENGYI4 and bululu5 the existence of these two data.

Basic tutorial for Python operation MySQL

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.