Python连接MySQL的基本步骤
1. 安装Python MySQL驱动
要连接MySQL数据库,首先需要安装Python MySQL驱动。Python MySQL驱动有多种选择,常用的有PyMySQL和mysql-connector-python。在这里我们以mysql-connector-python为例。安装方法为:
```
pip install mysql-connector-python
2. 连接MySQL数据库
连接MySQL数据库需要用到mysql.connector模块中的connect()方法。connect()方法需要传入MySQL数据库的连接参数,包括host、user、password和database等。示例代码如下:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
print(mydb)
3. 创建数据库和表
在连接成功后,如果需要创建数据库和表,可以通过执行SQL语句来实现。示例代码如下:
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
4. 插入数据
使用INSERT语句可以向表中插入数据。示例代码如下:
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
5. 查询数据
使用SELECT语句可以查询表中的数据。示例代码如下:
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
以上就是Python连接MySQL的基本步骤。除此之外,还可以通过Python操作数据库实现更多的功能,例如更新数据、删除数据、事务处理等。Python作为一种强大的编程语言,在操作MySQL数据库方面也有着非常大的优势。
相关词:
- Python
- MySQL
- 数据库连接
- PyMySQL
- mysql-connector-python
- connect()
- CREATE DATABASE
- CREATE TABLE
- INSERT
- SELECT
网友留言(0)