1、pymysql
(1)连接
import pymysql
# 指定编码格式,否则运行结果出现乱码
conn = pymysql.connect(user="root", password="root", database="py_taobao", charset="utf8")
print("数据库连接成功")
(2)查询
cursor = conn.cursor()
sql = "select * from goods limit 0,6"
cursor.execute(sql)
result = cursor.fetchall()
for row in result:
print(result)
cursor.close()
conn.close()
2、mysql-connector-python
(1)连接
import mysql.connector
conn = mysql.connector.connect(user="root", password="root", database="py_taobao")
print("连接数据库成功")
(2)查询,同方式一
3、sqlalchemy
(1)连接
import pymysql
from sqlalchemy import create_engine
pymysql.install_as_MySQLdb()
# 创建引擎对象
engine = create_engine("mysql://root:root@localhost/py_taobao?charset=utf8")
print("连接数据成功")
(2)查询
from sqlalchemy.orm import sessionmaker
# 创建会话对象
Session = sessionmaker(bind=engine)
session = Session()
# 输出前五条记录
sql = "select * from goods limit 5"
result = session.execute(sql)
for row in result:
print(row)
session.close()
网友评论