MySQL is a good open source database, it is now widely used, so it is necessary to briefly introduce the MySQL database using Python methods. Python operations database requires a third party module to be installed, with downloads and documentation in http://mysql-python.sourceforge.net/.
Since Python's database module has a specific database module specification, there is a demonstration of the code in the same way, regardless of which database is used:
#-*-encoding:gb2312-*-import OS, sys, string import mysqldb # Connection Database Try:conn = mysqldb.connect (host= ' localhost ', User= ' root ', passwd= ' xxxx ', db= ' test1 ') except Exception, E:print e sys.exit () # Get Cursor object to operate cursor = Conn.cursor () # Creating Table sql = "CREATE table if not exists test1 (name varchar (128) primary key, age int (4))" Cursor.execute (SQL) # Insert Data sq L = "INSERT into test1 (name, age) VALUES ('%s ',%d)"% ("Zhaowei") try:cursor.execute (SQL) except Exception, e:p rint e sql = "INSERT into test1 (name, age) VALUES ('%s ',%d)"% ("John," Try:cursor.execute (SQL) except Exception, E
: Print e # insert Multiple sql = INSERT into test1 (name, age) values (%s,%s) val = (("Dick", 24), ("Harry", 25), ("Hong Liu,") Try: Cursor.executemany (SQL, Val) except Exception, e:print e #查询出数据 sql = "SELECT * from Test1" cursor.execute (SQL) ALLD ATA = Cursor.fetchall () # If there is data returned, loop output, AllData is a two-dimensional list if Alldata:for rec in Alldata:print rec[0], rec[1] Curs Or.close () Conn.close ()