利用pymysql從資料庫中讀資料,並訪問list

2021-09-25 22:17:25 字數 694 閱讀 4338

def read_data_from_db():

# 連線配置資訊

db = pymysql.connect(host='',

port=,

user='',

password='',

db='',

charset='utf8',

cursorclass=pymysql.cursors.dictcursor)

# 建立連線

# con= pymysql.connect(**config)

# 執行sql語句

cursor = db.cursor() # 使用cursor()方法獲取操作游標

sql = "select * from pt_all_data"

cursor.execute(sql)

info = cursor.fetchall()

db.commit()

cursor.close() # 關閉游標

db.close() # 關閉資料庫連線

return info

一般從資料庫中讀出的資料是元組型別的,為了讀的資料是list型別的需要加入cursorclass=pymysql.cursors.dictcursor,就可以把資料讀出來,list的物件是字典型別的。

參考文章:

pymysql的使用 從資料庫獲取資料

一 pymysql從資料庫獲取資料 1.匯入pymysql包 import pymysql2.建立資料庫連線 connect pymysql.connect host host,port port,user dbuser,password pwd,database db 注意 引數host port...

pymysql 資料庫操作

參考文件 import pymysql dbparams conn pymysql.connect dbparams cursor conn.cursor sql select sname,sclass from student try cursor.execute sql 獲取查詢結果 data ...

pymysql連線資料庫

建立資料庫 import pymysql 開啟資料庫連線 db pymysql.connect localhost testuser test123 testdb 使用 cursor 方法建立乙個游標物件 cursor cursor db.cursor 使用 execute 方法執行 sql,如果表...