print("python连接mysql数据库")
# import mysql.connector
"""
#1 使用mysql-connector连接mysql
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="clever",
passwd="1881301",
database="clever"
)
mycursor = mydb.cursor()
mycursor.execute("show databases")
print(mycursor.fetchall())
print(mydb)
"""
"""
# 2 使用pymysql连接mysql
import pymysql
# 打开数据库连接
db = pymysql.connect(host="localhost",
user="clever",
password="1881301",
database="clever")
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询
sql = "SELECT VERSION()"
cursor.execute(sql)
# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
print("Database version : %s " % data)
# 关闭数据库连接
db.close()
"""
"""
#3 使用SQLAlchemy
"""
from sqlalchemy import Column, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# 创建对象的基类:
Base = declarative_base()
# 定义User对象:
class User(Base):
# 表的名字:
__tablename__ = 'user'
# 表的结构:
id = Column(String(20), primary_key=True)
name = Column(String(20))
# 初始化数据库连接:
host="localhost"
user="clever"
password="1881301"
database="clever"
engine = create_engine('mysql+pymysql://{}:{}@{}:3306/{}'.format(user,password,host,database))
# 创建DBSession类型:
DBSession = sessionmaker(bind=engine)
# 添加一条记录
# 创建session对象:
session = DBSession()
# 建库
# session
# 创建新User对象:
new_user = User(id='5', name='Bob')
# 添加到session:
session.add(new_user)
# 提交即保存到数据库:
session.commit()
# 关闭session:
session.close()
标签:clever,数据库,cursor,session,user,mysql,import,python3
From: https://blog.51cto.com/u_14011026/6190396