python连接mysql的三种方式

pymysql 连接 mysql 数据库

  • 此方式连接mysql服务器,方法简明直接,但是操作数据库,需要使用mysql数据的语法较为不便。
# Pymysql 连接 mysql 数据库
import pymysql

# 打开数据库连接
# mysql> CREATE DATABASE testbase

db = pymysql.connect(host='localhost',user='root',database='testbase',password='******',charset='utf8')

try:
    # 使用db.cursor()方法创建一个游标对象cursor
    with db.cursor() as cursor:
        sql = """SELECT VERSION()"""
        # 使用execute()方法执行SQL查询
        cursor.execute(sql)
        res = cursor.fetchone()
    db.commit()

except Exception as e:
    print (f'fetch error{e}')

finally:
    # 关闭数据连接
    db.close()

print (f'Database version : {res}')

sqlalchemy 连接 mysql 数据库

  • sqlalchemy的core方式比ORM方式更为底层。
import pymysql
from sqlalchemy import create_engine,Table,Column,Integer,String,MetaData,ForeignKey

# echo = True 开启调试
engine = create_engine("mysql+pymysql://root:xsh123456@localhost/testbase",echo=True)

# 创建元数据
metadata = MetaData(engine)

book_table = Table('book',metadata,
                   Column('id',Integer,primary_key=True),
                   Column('name',String(20)))

author_table = Table('author',metadata,
                     Column('id',Integer,primary_key=True),
                     Column('book_id',None,ForeignKey('book.id')),
                     Column('author_name',String(128),nullable=False))

try:
    metadata.create_all()
except Exception as e:
    print (f"create error{e}")

ORM 方式连接 mysql 数据

  • sqlalchemy的ORM方式,更贴近实际应用,使用频次最高
import pymysql
from sqlalchemy import create_engine,Table,Column,Integer,String,MetaData,ForeignKey,DateTime
from sqlalchemy.ext.declarative import declarative_base
from datetime import datetime


Base = declarative_base()

class Book_table(Base):
    __tablename__ = 'bookorm'
    book_id = Column(Integer(),primary_key=True)
    book_name = Column(String(50),index=True)

class Author_table(Base):
    __tablename__ = 'authororm'
    user_id = Column(Integer(),primary_key=True)
    username = Column(String(15),nullable=False,unique=True)
    create_on = Column(DateTime(),default=datetime.now)
    update_on = Column(DateTime(),default=datetime.now,onupdate=datetime.now)

# 实例化一个引擎
dburl = 'mysql+pymysql://root:xsh123456@localhost/testbase?charset=utf8mb4'
engine = create_engine(dburl,echo=True,encoding='utf-8')

Base.metadata.create_all(engine)
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python连接MySQL的步骤如下: 1. 安装Python MySQL驱动程序 Python MySQL驱动程序有多种可选,常用的有: - mysql-connector-python - PyMySQL - mysqlclient 可以使用pip安装: ``` pip install mysql-connector-python ``` 2. 导入MySQL驱动程序 使用Python连接MySQL需要导入MySQL驱动程序,例如使用mysql-connector-python: ```python import mysql.connector ``` 3. 建立连接Python连接MySQL需要指定MySQL服务器的IP地址、用户名、密码、端口号等信息,并使用mysql.connector.connect()方法建立连接。例如: ```python mydb = mysql.connector.connect( host="localhost", user="root", password="password", database="mydatabase" ) ``` 其中,host为MySQL服务器的IP地址,user和password为登录MySQL的用户名和密码,database为要连接数据库名称。 4. 创建游标对象 建立连接后,需要创建游标对象以执行SQL语句。例如: ```python mycursor = mydb.cursor() ``` 5. 执行SQL语句 使用游标对象执行SQL语句。例如: ```python mycursor.execute("SELECT * FROM customers") ``` 6. 获取查询结果 使用fetchall()方法获取查询结果。例如: ```python result = mycursor.fetchall() for row in result: print(row) ``` 完整示例代码: ```python import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", password="password", database="mydatabase" ) mycursor = mydb.cursor() mycursor.execute("SELECT * FROM customers") result = mycursor.fetchall() for row in result: print(row) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值