import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
image.png
db = MySQLdb.connect("127.0.0.1", "root", "123456", "50exercise")
cursor = db.cursor()
sql = "SELECT * FROM 50exercise.course;"
try:
# 执行sql语句
cursor.execute(sql)
results = cursor.fetchall()
print(results)
except:
# 发生错误时回滚
db.rollback()
# 关闭数据库连接
db.close()
image.png
与pandas 联动
import pandas as pd
# 下面传入的参数依次是(ip,username,userpassword,databases)
conn = pymysql.connect("127.0.0.1", "root", "123456", "50exercise")
sql = "SELECT * FROM 50exercise.course;"
df=pd.read_sql_query(sql,conn)
print(df.head())
image.png
网友评论