Python与MySQL连接
生活随笔
收集整理的這篇文章主要介紹了
Python与MySQL连接
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
import MySQLdb #注意大小寫!!
#建立和數(shù)據(jù)庫系統(tǒng)的連接
conn = MySQLdb.connect(host='localhost',user='root',passwd='smile',db='test')
#獲取操作游標(biāo)
cursor = conn.cursor()
#執(zhí)行SQL,創(chuàng)建一個數(shù)據(jù)庫.
cursor.execute("""create database python""")
cursor.execute('create table test')
#生成插入?yún)?shù)值
values=[]
for i in range(20):
values.append((i,'Hello mysqldb, I am recoder ' + str(i)))
#插入多條記錄
cursor.executemany('''insert into test values(%s,%s)''',values);
#提交修改
conn.commit()
count = cursor.execute('select * from test')
results = cursor.fectchmany(5)
#重置游標(biāo)位置,0,為偏移量,mode=absolute | relative,默認(rèn)為relative,
cursor.scroll(0,mode='absolute')
results = cursor.fetchall()
#關(guān)閉連接,釋放資源
cursor.close();
#建立和數(shù)據(jù)庫系統(tǒng)的連接
conn = MySQLdb.connect(host='localhost',user='root',passwd='smile',db='test')
#獲取操作游標(biāo)
cursor = conn.cursor()
#執(zhí)行SQL,創(chuàng)建一個數(shù)據(jù)庫.
cursor.execute("""create database python""")
cursor.execute('create table test')
#生成插入?yún)?shù)值
values=[]
for i in range(20):
values.append((i,'Hello mysqldb, I am recoder ' + str(i)))
#插入多條記錄
cursor.executemany('''insert into test values(%s,%s)''',values);
#提交修改
conn.commit()
count = cursor.execute('select * from test')
results = cursor.fectchmany(5)
#重置游標(biāo)位置,0,為偏移量,mode=absolute | relative,默認(rèn)為relative,
cursor.scroll(0,mode='absolute')
results = cursor.fetchall()
#關(guān)閉連接,釋放資源
cursor.close();
轉(zhuǎn)載于:https://www.cnblogs.com/wangshide/archive/2011/09/15/2178073.html
總結(jié)
以上是生活随笔為你收集整理的Python与MySQL连接的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#实现像微信PC版一样的扫码登录功能
- 下一篇: Win7下提取加密PDF文件(pdf加密