1.import MySQLdb;
2.与mysql数据库建立连接:con=MySQLdb.connect(user='root',db='mysql',passwd='dingjia',host='localhost')
3.当没有游标cursor对象时候,连接对象可以使用query()方法,执行sql查询
con.query('create database test')
4.使用游标对象和execute()方法来执行sql
cur=con.cursor() 返回游标对象
cur.execute('create table users(login varchar(8),uid INT)')
cur.execute('insert into users values('hzhida',1000)')
cur.execute('select *from users')
for data in cur.fetchall(): 输出查询结果得到的数据
print '%s\t%s' % data
cur.close() 关闭游标
con.commit() 提交事务
con.close() 关闭连接
python cookbook 的例子:
#-*-coding:utf-8-*- import MySQLdb,cPickle #连接到数据库,并获得图标 connection = MySQLdb.connect(user = 'root',db='zm',passwd = '36039975',host='localhost') cursor = connection.cursor() #创建一个新表以用于试验 cursor.execute('create table test(name TEXT, ablob BLOB)') try: #准备一些BLOB用于测试 names = 'aramis', 'athos','porthos' data = { } for name in names: datum = list(name) datum.sort() data[name] = cPickle.dumps(datum,2) #execute insert sql = "insert into test values(%s, %s)" for name in names: cursor.execute(sql,(name,MySQLdb.escape_string(data[name]))) #check in the database sql = "select name, ablob from test order by name" cursor.execute(sql) for name , blob in cursor.fetchall(): print name, cPickle.loads(blob), cPickle.loads(data[name]) finally: #finish,delete table and close connection cursor.execute("drop table test") cursor.close() connection.close()
输出:
aramis ['a', 'a', 'i', 'm', 'r', 's'] ['a', 'a', 'i', 'm', 'r', 's']
athos ['a', 'h', 'o', 's', 't'] ['a', 'h', 'o', 's', 't']
porthos ['h', 'o', 'o', 'p', 'r', 's', 't'] ['h', 'o', 'o', 'p', 'r', 's', 't']