python将数据存入mysql代码
时间: 2023-09-11 10:11:12 浏览: 132
python将数据存入mysqld数据库
下面是一个简单的 Python 程序,用于将数据存储到 MySQL 数据库中:
1. 安装 MySQL 驱动程序
```python
pip install mysql-connector-python
```
2. 连接到 MySQL 数据库
```python
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
```
3. 创建一个表格
```python
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
```
4. 插入数据
```python
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
```
完整代码示例:
```python
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
```
请替换 `host`, `user`, `password`, `database` 和插入数据的值以适应你自己的情况。
阅读全文