安裝python MySQL環境
阿新 • • 發佈:2019-01-07
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']