python3查詢mysql數據


python3不支持MySQLdb,代替的是import pymysql

連接數據庫查表:

import pymysql
conn= pymysql.connect(
host='xx.xx.xx.xx',
port = 3306,
user='xxx',
passwd='xxx',
db ='transit',
)
cur = conn.cursor()
cur.execute("SELECT * FROM xxx")
for r in cur.fetchall():
print(r)
#cur.close()
conn.close()

 

或者

#1. mysql connetct
host = "xxx.xxx.xxx.xxx"
user = "xxx"
passwd = "xxx"
port = 3306
db = "transit"

conn = MySQLdb.connect(host=host,port=port,user=user,passwd=passwd,db=db,charset='utf8', )

#2. create cursour
cursor = conn.cursor()

#3. query
sql = "select * from xxx"
try:
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
id = row[0]
stream_name = row[1]
download_url = row[2]
size = row[3]
status = row[4]
createAt = row[5]
print(id,stream_name,download_url,size,status,createAt)
#print ("id=%s,stream_name=%s,download_url=%s,size=%s,status=%d,createAt=%s"%(id, stream_name, download_url, size, status,createAt))
except:
print ("Error: unable to fetch data")
# close mysql
conn.close()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM