import MySQLdb
import pprint
# 創(chuàng)建一個Connection對象敛苇,代表了一個數(shù)據(jù)庫連接
connection = MySQLdb.connect(
? ? ? ? ? ? ? ? ? ? ? ? ? ? host='129.***.**.43',? # 數(shù)據(jù)庫ip地址
? ? ? ? ? ? ? ? ? ? ? ? ? ? user='root',? ? ? ? # mysql用戶名
? ? ? ? ? ? ? ? ? ? ? ? ? ? passwd='******', # mysql用戶登錄密碼
? ? ? ? ? ? ? ? ? ? ? ? ? ? db='****',? ? ? ? # 數(shù)據(jù)庫名
? ? ? ? ? ? ? ? ? ? ? ? ? ? # 如果數(shù)據(jù)庫里面的文本是utf-8編碼渺贤,需要切換編碼格式
? ? ? ? ? ? ? ? ? ? ? ? ? ? charset='utf8'? ? ? # charset指定是utf8
? ? ? ? ? ? ? ? ? ? ? ? ? ? )
# 創(chuàng)建一個游標(biāo)對象
c = connection.cursor()
# rowcount 方法
?c.execute("SELECT * FROM student3") # 輸入SQL命令
?pprint.pprint(c.rowcount) # rowcount:顯示多少行記錄
?for x in range(c.rowcount):
? ? ?row = c.fetchone()
? ? ?pprint.pprint(row)
# fetchall 和 fetchone 方法
?c.execute("SELECT * FROM student3") # 輸入SQL命令
?rows = c.fetchall() # 獲取所有的信息
?rows = c.fetchone() # fetchone:獲取一行信息,默認(rèn)第一行
?pprint.pprint(rows)
?# fetchmany 方法
c.execute("SELECT * FROM student3 where mobilephone='18796650404'") # 輸入SQL命令
rows = c.fetchmany(c.rowcount) # rowcount:顯示多少行。 fetchmany:打印多少行信息
pprint.pprint(rows)
ps:
1.系統(tǒng)默認(rèn)查詢返回的是元組形式
2.如果需要讀取成字典形式啤咽,在創(chuàng)建游標(biāo)時修改即可
c = connection.cursor(cursor=pymysql.cursors.DictCursor)