一、基本操作
import mysql.connector #导入MySQL驱动
#打开数据库 first
conn = mysql.connector.connect(user='root', password='password', database='first')
cursor = conn.cursor() #创建一个浮标
cursor.execute('create table user (id varchar(20) primary key, name varchar(20))') #创建user表
cursor.execute('insert into user (id,name) values (%s, %s)',['1', 'Guoguo']) #插入一行数据
#注意MySQL的占位符是%s
cursor.rowcount #返回操作的行数
#1
cursor.execute('update user set name = %s where id = 1',('LinYun',)) #更改表中数据
cursor.execute('delete from user where id = 1') #删除表中数据
conn.commit() #将操作提交到数据库
cursor.close() #关闭连接
cursor = conn.cursor() #重新建立连接
cursor.execute('select * from user where id = %s',('1',)) #运行查询
values = cursor.fetchall() #取出所查询到的
values #输出所查询到的
cursor.close() #关闭cursor
conn.close() #关闭connection
二、多线程存取Mysql数据
创建表
>>> import mysql.connector
>>> conn = mysql.connector.connect(user='root', password='password', database='thread') # 打开数据库 thread
>>> cursor = conn.cursor()
>>> cursor.execute('create table threading (operation varchar(100) primary key, name varchar(500))') # 创建 threading 表
>>> conn.commit()
>>> cursor.close()
True
(一)多线程存入数据
import mysql.connector
import datetime
import time
import threading
def insert(io):
time_now = datetime.datetime.now()
print(io, time_now)
conn = mysql.connector.connect(user='root', password='password', database='thread')
cursor = conn.cursor()
cursor.execute("insert into threading values (%s, %s)",[io ,time_now])
cursor.close()
conn.commit()
time.sleep(5)
if __name__ == "__main__":
t = threading.Thread(target=insert, args=('in',))
t.start()
t = threading.Thread(target=insert, args=('out',))
t.start()
t.join()
这是在一个表中多线程插入数据
最好是多线程建表和插入 数据