MySQLdb的使用。
1.create table:
#-*- coding:utf-8 -*-
'''
@data:2015-01-05
@filename:CreateTable.py
'''
import MySQLdb as mdb
import sys
con = None
try:
con = mdb.connect('localhost','root','123456','py')
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS \
Writers(Id INT PRIMARY KEY AUTO_INCREMENT,Name VARCHAR(25))")
cur.execute("INSERT INTO Writers(Name) VALUES('Jack London')")
cur.execute("INSERT INTO Writers(Name) VALUES('Honore de Balzac')")
cur.execute("INSERT INTO Writers(Name) VALUES('Lion')")
cur.execute("INSERT INTO Writers(Name) VALUES('Emile')")
cur.execute("INSERT INTO Writers(Name) VALUES('Truman Capote')")
print "Database Table Writes Create success."
finally:
if con:
con.close()
2.select table
#-*- coding:utf-8 -*-
'''
@data:2015-01-05
@filename:SelectTable.py
'''
import MySQLdb as mdb
import sys
con = None
try:
con = mdb.connect('localhost','root','123456','py')
cur = con.cursor()
cur.execute("SELECT * FROM Writers")
numrows = int(cur.rowcount)
for i in range(numrows):
row = cur.fetchone()
print row[0],'|',row[1]
finally:
if con:
con.close()