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()

 

posted @ 2017-07-21 17:08  韩家姐姐  阅读(6843)  评论(0编辑  收藏  举报