python mysql多线程
时间: 2023-11-21 13:56:51 浏览: 83
python多线程
使用Python的`threading`模块可以实现MySQL多线程操作。下面是一个简单的例子,其中两个线程分别执行查询和插入操作:
```python
import threading
import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="123456",
database="mydatabase"
)
# 查询操作
def select_data():
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
# 插入操作
def insert_data():
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, "记录插入成功。")
# 创建线程
t1 = threading.Thread(target=select_data)
t2 = threading.Thread(target=insert_data)
# 启动线程
t1.start()
t2.start()
# 等待线程结束
t1.join()
t2.join()
```
阅读全文