python 之mysql(多條數(shù)據(jù)插入,獲取多條數(shù)據(jù)fetchone()or fetchall())

#!/usr/bin/env python

#coding:utf-8

import MySQLdb

'''

#打開數(shù)據(jù)庫鏈接

conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='07day05db')

# 使用cursor()方法獲取操作游標(biāo)

cur = conn.cursor()

# 使用execute方法執(zhí)行SQL語句

reCount = cur.execute('insert into UserInfo(Name,Address) values(%s,%s)',('alex','usa'))

# 提交到數(shù)據(jù)庫執(zhí)行

conn.commit()

cur.close()

conn.close()

print reCount

'''

'''

conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='07day05db')

cur = conn.cursor()

reCount = cur.execute('delete from UserInfo')

conn.commit()

cur.close()

conn.close()

print reCount

'''

'''


conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='07day05db')

cur = conn.cursor()

#插入多條數(shù)據(jù)數(shù)據(jù)庫

li =[

? ? ('alex','usa'),

? ? ('sb','usa'),

]

reCount = cur.executemany('insert into UserInfo(Name,Address) values(%s,%s)',li)

conn.commit()

cur.close()

conn.close()

print reCount

'''

'''

conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='07day05db')

cur = conn.cursor()

reCount = cur.execute('update UserInfo set Name = %s',('alin',))

conn.commit()

cur.close()

conn.close()

print reCount

'''

'''

#fetchone/fetchmany(num)?

conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='07day05db')

cur = conn.cursor()

reCount = cur.execute('select * from UserInfo')

print cur.fetchone()

print cur.fetchone()

#絕對定位

cur.scroll(-1,mode='absolute')

#相對定位

cur.scroll(-1,mode='relative')

print cur.fetchone()

print cur.fetchone()

cur.scroll(0,mode='absolute')

# 使用 fetchone() 方法獲取一條數(shù)據(jù)

print cur.fetchone()

print cur.fetchone()

cur.close()

conn.close()

print reCount

'''

Python查詢Mysql使用 fetchone() 方法獲取單條數(shù)據(jù), 使用fetchall() 方法獲取多條數(shù)據(jù)。

fetchone():?該方法獲取下一個(gè)查詢結(jié)果集。結(jié)果集是一個(gè)對象

fetchall():接收全部的返回結(jié)果行.

rowcount:?這是一個(gè)只讀屬性,并返回執(zhí)行execute()方法后影響的行數(shù)。

#fetchall

conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='07day05db')

#以字典的方式填充結(jié)果cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)

#cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)

cur = conn.cursor()

reCount = cur.execute('select Name,Address from UserInfo')

nRet = cur.fetchall()

cur.close()

conn.close()

print reCount

print nRet

for i in nRet:

? ? print i[0],i[1]

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容