如何使用Python连接MySQL数据库mysqlconnet

一,使用Python连接MySQL数据库 为了开始连接MySQL数据库,我们首先需要具备操作MySQL的credential(凭据)。在MySQL Connector中,这些凭据指的是主机名、用户名、密码等信息。以下是连接MySQL数据库的示例代码:import mysql.connector mydb = mysql.connector.connect(host=”localhost”,user=&#...
如何使用Python连接MySQL数据库mysqlconnet
如何使用Python连接MySQL数据库?
MySQL是一种免费的关系型数据库,被广泛应用于各种应用程序中。Python作为一种流行的编程语言,也具备了与MySQL数据库交互的能力。本文将探讨如何使用Python连接MySQL数据库及执行一些基本的数据库操作。
我们需要安装MySQL的Python Connector才能在Python中使用MySQL数据库。可以在终端命令行中使用以下命令进行安装:
pip install mysql-connector-python
一,使用Python连接MySQL数据库
为了开始连接MySQL数据库,我们首先需要具备操作MySQL的credential(凭据)。在MySQL Connector中,这些凭据指的是主机名、用户名、密码等信息。以下是连接MySQL数据库的示例代码:
import mysql.connector
mydb = mysql.connector.connect(
host=”localhost”,
user=”yourusername”,
password=”yourpassword”
)
如果连接成功,我们就可以得到代表连接的对象mydb。
二,Python与MySQL的基本交互方式
2.1 创建数据库
接下来,我们要学习如何在Python中创建一个MySQL数据库。使用以下代码可以创建一个名为mydatabase的数据库:
import mysql.connector
mydb = mysql.connector.connect(
host=”localhost”,
user=”yourusername”,
password=”yourpassword”
)
mycursor = mydb.cursor()
mycursor.execute(“CREATE DATABASE mydatabase”)
2.2 创建表格
为了创建一个表格,在Python中需要使用CREATE TABLE语句。以下是一个示例代码:
import mysql.connector
mydb = mysql.connector.connect(
host=”localhost”,
user=”yourusername”,
password=”yourpassword”,
database=”mydatabase”
)
mycursor = mydb.cursor()
mycursor.execute(“CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))”)
这个代码段创建了名为customers的表格,并且包含两个列:name和address。
2.3 插入数据
对于建立好的表格,我们需要使用INSERT INTO语句来向其中添加数据。以下是一个示例代码:
import mysql.connector
mydb = mysql.connector.connect(
host=”localhost”,
user=”yourusername”,
password=”yourpassword”,
database=”mydatabase”
)
mycursor = mydb.cursor()
sql = “INSERT INTO customers (name, address) VALUES (%s, %s)”
val = (“John”, “Highway 21”)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, “record inserted.”)
在这个示例中,我们添加了一个名为John的用户,地址为Highway 21。
2.4 查询数据库
查询数据库使用SELECT语句。以下代码段为我们展示如何使用Python查询MySQL数据库。
import mysql.connector
mydb = mysql.connector.connect(
host=”localhost”,
user=”yourusername”,
password=”yourpassword”,
database=”mydatabase”
)
mycursor = mydb.cursor()
mycursor.execute(“SELECT * FROM customers”)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
这段代码查询了customers表格,然后打印出所有数据。
2.5 删除数据
可以使用DELETE语句从MySQL表格中删除数据。以下是一个示例代码:
import mysql.connector
mydb = mysql.connector.connect(
host=”localhost”,
user=”yourusername”,
password=”yourpassword”,
database=”mydatabase”
)
mycursor = mydb.cursor()
sql = “DELETE FROM customers WHERE address = ‘Mountn 21′”
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, “record(s) deleted”)
这个示例代码删除了地址为Mountn 21的客户的行。
三,Python与MySQL高级交互方式
3.1 数据库批量操作
在实际生产环境中,通常需要一次性对MySQL数据库中的多行进行操作。MySQL Connector提供了executemany()函数实现批量操作。以下是一个示例代码:
import mysql.connector
mydb = mysql.connector.connect(
host=”localhost”,
user=”yourusername”,
password=”yourpassword”,
database=”mydatabase”
)
mycursor = mydb.cursor()
sql = “INSERT INTO customers (name, address) VALUES (%s, %s)”
val = [
(‘Peter’, ‘Lowstreet 4’),
(‘Amy’, ‘Apple st 652’),
(‘Hannah’, ‘Mountn 21’),
(‘Michael’, ‘Valley 345’),
(‘Sandy’, ‘Ocean blvd 2’),
(‘Betty’, ‘Green Grass 1’),
(‘Richard’, ‘Sky st 331’),
(‘Susan’, ‘One way 98’),
(‘Vicky’, ‘Yellow Garden 2’),
(‘Ben’, ‘Park Lane 38’),
(‘William’, ‘Central st 954’),
(‘Chuck’, ‘Mn Road 989’),
(‘Viola’, ‘Sideway 1633’)
]
mycursor.executemany(sql, val)
mydb.commit()
print(mycursor.rowcount, “was inserted.”)
使用executemany()函数可以一起向MySQL数据库中添加多行,大大减少了代码行数。
3.2 数据库事务处理
在Python与MySQL的交互中,可能由于程序崩溃或其他原因导致MySQL操作失败。在这种情况下,可以通过MySQL事务处理从而避免数据丢失或者逻辑错误。以下是在Python中使用MySQL事务处理的示例代码:
import mysql.connector
mydb = mysql.connector.connect(
host=”localhost”,
user=”yourusername”,
password=”yourpassword”,
database=”mydatabase”
)
mycursor = mydb.cursor()
mydb.start_transaction()
try:
mycursor.execute(“INSERT INTO customers (name, address) VALUES (‘John’, ‘Highway 21’)”)
mycursor.execute(“INSERT INTO customers (name, address) VALUES (‘Peter’, ‘Lowstreet 4’)”)
mydb.commit()
print(“Customer table updated!”)
except:
mydb.rollback()
print(“Rollbacked!”)
在上述代码中,使用MySQL的start_transaction()函数开启一个MySQL事务。如果MySQL操作失败,使用rollback()函数来回滚之前的操作。
使用Python连接MySQL数据库可以让我们在Python中轻松使用MySQL数据库,本文介绍了Python中MySQL数据库的基本和高级用法。2024-08-13
mengvlog 阅读 34 次 更新于 2025-08-11 11:58:53 我来答关注问题0
  •  翡希信息咨询 如何用python进行mysql的数据更新(大批量)?

    使用mysql.connector.connect方法建立与MySQL数据库的连接,并获取数据库游标。pythonimport mysql.connectorconn = mysql.connector.connectcursor = conn.cursor3. 编写SQL更新语句: 编写要执行的SQL更新语句,使用占位符%s来代表要插入的值。pythonsql = "UPDATE Writers SET Name = %s WHERE Id = %s"...

  • 首先确保Python环境中安装了mysql-connector-python库,如果未安装可以通过pip安装:pip install mysql-connector-python 然后建立与MySQL数据库的连接:python import mysql.connector conn = mysql.connector.connect(user='username', password='password', host='localhost', database='database_name')curso...

  •  云易网络科技 Python连接mysql数据库及python使用mysqldb连接数据库教程

    >>Sudo apt-get install mysql-client centOS/redhat >>yum install mysql 二,安装MySQL-python 要想使python可以操作mysql 就需要MySQL-python驱动,它是python 操作mysql必不可少的模块。 下载地址:https://pypi.python.org/pypi/MySQL-python/ 下载MySQL-python-1.2.5.zip 文件之后直接解压。进入MySQL-python-1....

  •  文暄生活科普 利用python如何能进行sqlite、mysql、postgresql进行curd

    MySQL 是一种广泛应用的 SQL 数据库管理系统,Python 可以通过 `mysql-connector-python` 库进行连接和交互。与 SQLite 类似,创建连接、表单、插入数据、选择数据、更新数据和删除数据的步骤如下:python import mysql.connector cnx = mysql.connector.connect(user='user', password='password',host='1...

  • python import pymysql 配置数据库连接参数 db_config = { 'host': 'localhost','port': 3306,'user': 'root','password': 'password123','db': 'test_db','charset': 'utf8mb4'} 连接数据库 connection = pymysql.connect(**db_config)使用连接执行SQL查询 cursor = connection.cursor()...

檬味博客在线解答立即免费咨询

Python相关话题

Copyright © 2023 WWW.MENGVLOG.COM - 檬味博客
返回顶部