如何使用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 阅读 11 次 更新于 2025-06-20 12:54:03 我来答关注问题0
  •  翡希信息咨询 利用python连接MySQL数据库并执行相关sql操作

    直接连接:使用Python的mysqlconnectorpython或PyMySQL等库,通过提供数据库连接信息来建立连接。执行SQL操作:查询操作:使用cursor.execute执行SELECT语句,并通过fetchall或fetchone等方法获取查询结果。插入操作:使用INSERT INTO语句,结合参数化查询来防止SQL注入攻击。更新操作:使用UPDATE语句,同样采用参数化...

  • 一,使用Python连接MySQL数据库 为了开始连接MySQL数据库,我们首先需要具备操作MySQL的credential(凭据)。在MySQL Connector中,这些凭据指的是主机名、用户名、密码等信息。以下是连接MySQL数据库的示例代码:import mysql.connector mydb = mysql.connector.connect(host=”localhost”,user=&#...

  •  云易网络科技 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环境中安装了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...

  •  文暄生活科普 通过pymysql中的connect()类创建Python与MySQL之间的连接

    要使用pymysql模块在Python与MySQL数据库之间建立连接,首先需要通过命令行安装pymysql:pip install pymysql 接下来,导入pymysql模块并创建连接:import pymysql conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123456', database='nocturneshop')创建游标对象以执行...

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

Python相关话题

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