python mysql储存
时间: 2023-07-09 08:47:41 浏览: 50
在Python中使用MySQL进行数据存储可以使用Python的MySQL Connector库来实现。下面是一个简单的示例代码,演示了如何使用Python连接MySQL数据库并执行一些基本的数据库操作。
首先需要安装MySQL Connector库,可以使用以下命令进行安装:
```
pip install mysql-connector-python
```
然后,可以使用以下代码连接到MySQL数据库:
```
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
print(mydb)
```
在连接到数据库后,可以执行各种数据库操作,例如创建表、插入数据、查询数据等。以下是一些示例操作:
创建表:
```
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
```
插入数据:
```
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.")
```
查询数据:
```
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
```
以上是一些基本的MySQL操作示例,可以根据具体需求进行修改和扩展。