Python 连接 MySQL

Python MySQL

简介

python可以使用mysql-connector库连接到mysql数据库,mysql-connector库是mysql官方推荐的python驱动,也可以使用pymysql库连接到mysql数据库,pymysql库是第三方驱动,功能更加丰富。

安装

pip install mysql-connector
pip install pymysql

使用mysql-connector

import mysql.connector

# 连接数据库
cnx = mysql.connector.connect(
    user="root", password="password", host="localhost", database="test"
)


# 创建游标
cursor = cnx.cursor()

# 创建表
sql = "CREATE TABLE students (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT)"
cursor.execute(sql)

# 插入数据
sql = "INSERT INTO students (name, age) VALUES (%s, %s)"
values = [("Tom", 20), ("Jerry", 25), ("Mike", 30)]
cursor.executemany(sql, values)


# 查询数据
sql = "SELECT * FROM students"
cursor.execute(sql)
for row in cursor.fetchall():
    print(row)


# 更新数据
sql = "UPDATE students SET age = %s WHERE name = %s"
values = (28, "Tom")
cursor.execute(sql, values)


# 删除数据
sql = "DELETE FROM students WHERE age < %s"
values = (25,)
cursor.execute(sql, values)


# 关闭游标和数据库连接
cursor.close()
cnx.close()

使用pymysql

import pymysql

# 连接数据库
cnx = pymysql.connect(
    user="root", password="password", host="localhost", database="test"
)

# 创建游标
cursor = cnx.cursor()

# 创建表
sql = "CREATE TABLE teachers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT)"
cursor.execute(sql)

# 插入数据
sql = "INSERT INTO teachers (name, age) VALUES (%s, %s)"
values = ("John", 25)
cursor.execute(sql, values)


# 查询数据
sql = "SELECT * FROM teachers"
cursor.execute(sql)
result = cursor.fetchall()
print(result)


# 更新数据
sql = "UPDATE teachers SET age = %s WHERE id = %s"
values = (30, 1)
cursor.execute(sql, values)


# 删除数据
sql = "DELETE FROM teachers WHERE id = %s"
values = (2,)
cursor.execute(sql, values)

# 关闭游标和数据库连接
cursor.close()
cnx.close()
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值