The Python MySQLdb module connects to the mysql database instance

  • 2020-05-07 19:56:31
  • OfStack

mysql is an excellent open source database. It is now widely used, so it is necessary to briefly introduce how to operate mysql database with python. The python operation database requires the installation of a 3rd party module, which is available for download and documentation in http:// mysql-python.sourceforge.net /.

Since the database module of python has a special specification for the database module, in fact, no matter which database method is used, it is more or less the same, here is a section of the code demonstration:


#-*- encoding: gb2312 -*-
import os, sys, string
import MySQLdb

#  Connect to database 
try:
  conn = MySQLdb.connect(host='localhost',user='root',passwd='xxxx',db='test1')
except Exception, e:
  print e
  sys.exit()

#  To obtain cursor Object to operate on 

cursor = conn.cursor()
#  Create a table 
sql = "create table if not exists test1(name varchar(128) primary key, age int(4))"
cursor.execute(sql)
#  Insert data 
sql = "insert into test1(name, age) values ('%s', %d)" % ("zhaowei", 23)
try:
  cursor.execute(sql)
except Exception, e:
  print e

sql = "insert into test1(name, age) values ('%s', %d)" % (" zhang 3", 21)
try:
  cursor.execute(sql)
except Exception, e:
  print e
#  Insert multiple 

sql = "insert into test1(name, age) values (%s, %s)" 
val = ((" li 4", 24), (" The king 5", 25), (" hong 6", 26))
try:
  cursor.executemany(sql, val)
except Exception, e:
  print e

# Query out data 
sql = "select * from test1"
cursor.execute(sql)
alldata = cursor.fetchall()
#  If any data is returned, the output is looped , alldata There is a 2 The list of d 
if alldata:
  for rec in alldata:
    print rec[0], rec[1]


cursor.close()

conn.close()


Related articles: