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 ()