Python MySQLdb module connects to and operates mysql database instances, mysqldbmysql

Source: Internet
Author: User

Python MySQLdb module connects to and operates mysql database instances, mysqldbmysql

Mysql is an excellent open-source database and is widely used. Therefore, it is necessary to briefly introduce how to operate mysql databases using python. A third-party module must be installed for python database operations. Download the package and documentation at http://mysql-python.sourceforge.net.

Because the python database module has specific database module specifications, no matter which database method is used, the following code is provided:

#-*-Encoding: gb2312-*-import OS, sys, stringimport MySQLdb # connect to the database try: conn = MySQLdb. connect (host = 'localhost', user = 'root', passwd = 'xxxx', db = 'test1') failed t Exception, e: print e sys. exit () # obtain the cursor object to operate cursor = conn. cursor () # create a table SQL = "create table if not exists test1 (name varchar (128) primary key, age int (4)" cursor.exe cute (SQL) # insert data SQL = "insert into test1 (name, age) values ('% s', % d)" % ("zhaowei", 23) try: cursor.exe cute (SQL) failed t Exception, e: print esql = "insert into test1 (name, age) values ('% s', % d)" % ("James", 21) try: cursor.exe cute (SQL) failed t Exception, e: print e # insert Multiple SQL statements = "insert into test1 (name, age) values (% s, % s) "val = (" Li Si ", 24), (" Wang Wu ", 25), (" Hong Liu ", 26) try: cursor.exe cute.pdf (SQL, val) failed t Exception, e: print e # query data SQL = "select * from test1" cursor.exe cute (SQL) alldata = cursor. fetchall () # if any data is returned, it will be output cyclically. alldata has a two-dimensional list. if alldata: for rec in alldata: print rec [0], rec [1] cursor. close () conn. close ()

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: info-contact@alibabacloud.com 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.