mysql入库出库代码
时间: 2023-07-09 21:39:07 浏览: 51
以下是使用 Python 连接 MySQL 数据库并进行插入和查询数据的示例代码:
1. 安装 mysql-connector-python 模块
```python
pip install mysql-connector-python
```
2. 连接数据库
```python
import mysql.connector
# 建立连接
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
# 获取游标
mycursor = mydb.cursor()
```
3. 插入数据
```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.")
```
4. 查询数据
```python
# 执行查询语句
mycursor.execute("SELECT * FROM customers")
# 获取查询结果
myresult = mycursor.fetchall()
# 输出查询结果
for x in myresult:
print(x)
```
5. 关闭连接
```python
# 关闭游标和连接
mycursor.close()
mydb.close()
```