python_操作MySQL 初解
单文件操作数据库
import random
import threading, multiprocessing
import time, datetime
import pymysql
import queue con = pymysql.Connect(
host='127.0.0.1', # IP配置
port=3306, # mysql端口号
user='root', # 用户名
passwd='', # 密码
db='test', # 连接数据库
charset='utf8' # 编码设置
)
cur = con.cursor() # 游标创建 d = {
"create": 'create table if not exists day1(card_id int, name VARCHAR(30), address VARCHAR(128)) default charset=utf8',
# 创建表
"insert": ['insert into day1(card_id,name,address) values(1,"Rose","北京")', # 插入数据
'insert into day1(card_id,name,address) values(2,"Jack","天津")',
'insert into day1(card_id,name,address) values(3,"张三","合肥")',
'insert into day1(card_id,name,address) values(4,"LiLy","河北")', ],
"select": 'select * from day1',
"drop": 'drop table if EXISTS day1',
} def for_out(cur): # 通过游标遍历将数据拿出
for row in cur:
print(row)
print() try:
print("初始化数据库")
print(d["drop"])
cur.execute(d["drop"])
print("开始创建表")
cur.execute(d["create"])
print("开始插入数据")
for i in d["insert"]:
print(i)
cur.execute(i)
a = datetime.datetime.now()
print(a)
time.sleep(3)
print("执行查询操作")
# for_out(cur)
b = datetime.datetime.now() except Exception as f:
print(f)
con.rollback()
q = queue.Queue() # 创建一个消息队列用来承接SQL语句 def for_1():
q.put(cur.execute(d["select"])) # 把查询到的结果放入消息队列
for_out(cur) # 查询放入的东西
print('********') # 标志线程1
print(b - a) # 打印运行时间 def for_2():
print('') # 标志线程2
while True:
q.get() # 从消息队列中拿出之前放入的东西 if __name__ == '__main__':
t1 = threading.Thread(target=for_1)
t2 = threading.Thread(target=for_2)
t1.start()
t2.start()
t1.join()
t2.join() cur.close()
con.close() # a = datetime.datetime.now()
# time.sleep(3)
# b = datetime.datetime.now()
# print(b-a)
# a1=time.time()
# time.sleep(3)
# b2 = time.time()
# print(b2-a1) # x = list(map(str,[1,2,3])
# )
# print(x)
# print(1,2,3,sep=',')
# print(True*3) # def sushu(name):
# print("函数功能")
# time.sleep(1)
# # print(name)
# print("函数名是%s" % threading.currentThread().name)
# l=[]
# Pool=[]
# for i in range(4):
# t = threading.Thread(target=sushu,name="%d线程"%i)
# l.append(t)
#
# for i in l:
# i.start()
#
# for i in l:
# i.join() #
# t1 =threading.Thread(target=sushu,args=(1,))
# t2 =threading.Thread(target=sushu,args=(2,))
# t3 =threading.Thread(target=sushu,args=(3,))
# t4 =threading.Thread(target=sushu,args=(4,))
#
# t1.start()
# # t1.join()
# t2.start()
# # t2.join()
# t3.start()
# # t3.join()
# t4.start()
# # t4.join()
# print("函数名是%s 运行了%d个线程 当前时间%s" % (threading.currentThread().name, threading.active_count(), time.ctime()))
# t1.join()
# t2.join()
# t3.join()
# t4.join() # a = random.randint(1, 20) * 100
# print(a)
# -*- coding: utf-8 -*-
# __author__ = "Allen"
import pymysql
con=pymysql.connect(
host="localhost",
user="root",
port=3306,
passwd="",
charset="utf8",
db="test"
)
cur=con.cursor()
sql={
"create":'create table if not exists shu(name char(15)not null,sex char(10),age int,score int)default charset="utf8"',
"insert":[
'insert into shu values("小王","男",26,97)',
'insert into shu values("小白","女",34,89)',
'insert into shu values("小黄","女",22,95)',
'insert into shu values("小黑","女",27,58)',
'insert into shu values("小刘","男",24,76)',
'insert into shu values("小讲","男",34,65)',
'insert into shu values("小班","男",42,79)'
],
"select":'select * from shu where sex="男";',
"select1":'select * from shu where sex="女";',
"select2":'select * from shu where score>80;',
"update":'update shu set age=age+2;',
"select3":'select * from shu;',
"delete":'delete from shu where name="小讲";',
"select4":'select * from shu order by age desc;',
"select5":'select * from shu order by age asc;',
"drop":'drop table if exists shu',
}
def for_out(cur):
for i in cur:
print(i)
print( )
try:
print("初始化数据库")
print(sql["create"])
cur.execute(sql["create"]) for j in sql["insert"]:
print(j)
cur.execute(j)
cur.execute(sql["select"])
for_out(cur) cur.execute(sql["select1"])
for_out(cur) cur.execute(sql["select2"])
for_out(cur) cur.execute(sql["update"])
for_out(cur)
cur.execute(sql["select3"])
for_out(cur)
cur.execute(sql["delete"])
for_out(cur)
cur.execute(sql["select4"])
for_out(cur)
cur.execute(sql["select5"])
for_out(cur)
cur.execute(sql["drop"])
for_out(cur)
except Exception as f:
print(f)
con.rollback()
con.close()
cur.close()
单文件操作MySQL
import pymysql
db=pymysql.connect(
host="localhost",
port=3306,
database="test",
user="root",
passwd="",
charset="utf8"
) #设置游标
cr=db.cursor()
sql_gn={"insert1":"insert commodity values(0,'iPhone6',2100,4.9,99,'富士康'),"
"(0,'iPhone6s',2900,4.9,101,'硅谷'),"
"(0,'iPhone6plus',3100,5.5,131,'上海'),"
"(0,'iPhone6sPlus',3400,5.5,150,'北京'),"
"(0,'iPhone7',3900,4.9,161,'天津'),"
"(0,'iPhone7Plus',4100,5.5,180,'重庆'),"
"(0,'iPhone8',4300,4.9,191,'四川'),"
"(0,'iPhone8Plus',4700,5.5,210,'沈阳'),"
"(0,'iPhoneX',5200,4.9,230,'广州'),"
"(0,'苹果',10.5,2,200,'富士山'),"
"(0,'梨',5.5,2.5,210,'烟台'),"
"(0,'香蕉',7.5,3,193,'泰安'),"
"(0,'荔枝',235,5,213,'贵州'),"
"(0,'核桃',25.5,0.7,217,'邯郸'),"
"(0,'柚子',11,6.2,219,'广西'),"
"(0,'西瓜',2.5,6.7,220,'郑州'),"
"(0,'葡萄',7.9,0.3,230,'大理'),"
"(0,'提子',5.5,0.4,231,'濮阳'),"
"(0,'哈密瓜',30,4.8,130,'南海'),"
"(0,'椰子',35,4.6,121,'安阳'),"
"(0,'猕猴桃',21,2.1,131,'焦作'),"
"(0,'桃子',2.7,3.1,232,'大名'),"
"(0,'杏',2.2,1.7,233,'邢台'),"
"(0,'芒果',21,3.2,234,'永年'),"
"(0,'点心',35,2.3,3099,'石家庄'),"
"(0,'玉米',0.7,0.6,235,'沧州'),"
"(0,'无线鼠标',170,1.3,234,'廊坊'),"
"(0,'无线键盘',190,7.8,237,'霸州'),"
"(0,'三星显示器',7100,52,238,'湖南'),"
"(0,'小米耳机',149,1.2,239,'湖北');",
"delete1":"delete from commodity where ID%2=0;",
"select1":"select * from commodity where price<20;",
"update1":"update commodity set price=70 where price<20;",
"update2":"update commodity set price=1 where price=30;",
"delete2":"delete from commodity where ID=11 or ID=13;",
"update3":"update commodity set price=price*0.7",
"insert2":"insert commodity values(0,'手机',2300,5.5,199,'杭州'),"
"(0,'华为',3100,4.5,102,'中关村');",
"select2":"select * from commodity where goods_name='手机';",
"select3":"select count(*) from commodity;",
"delete3":"delete from commodity where ads='湖南' or ads='湖北';",
"update4":"update commodity set price=price*1.3 where goods_name like '%点心%' and price<100;",
"update5":"update commodity set goods_name=replace(goods_name,'手机','移动电话');"}
try:
cr.execute(sql_gn["insert1"])#插入30条记录
cr.execute(sql_gn["delete1"])#删除ID是偶数的商品
cr.execute(sql_gn["update2"])#把所有价格为30的商品库存修改为1
cr.execute(sql_gn["delete2"])#删除id是11,13的记录
cr.execute(sql_gn["update3"])#所有商品价格减少百分之30
cr.execute(sql_gn["delete3"])#删除产地是“湖南”,”湖北”的商品
cr.execute(sql_gn["update4"]) # 把含有‘点心’的商品价格上调百分之30如果价格超过100元则该商品不上调
cr.execute(sql_gn["select1"]) # 先查询商品价格小于20的记录
x = cr.fetchall()
print(x)
cr.execute(sql_gn["update1"]) # 这部分的商品价格改为70
cr.execute(sql_gn["insert2"]) # 添加2个新的商品
cr.execute(sql_gn["select2"]) # 显示商品名中包含’手机’两字的商品
x1 = cr.fetchall()
print(x1)
cr.execute(sql_gn["update5"]) # 将手机改为移动电话
cr.execute(sql_gn["select3"])
x2=cr.fetchall()
print(x2)
cr.execute(sql_gn["update4"])
except Exception as ex:
print("写入异常")
db.rollback()
cr.close()
db.close()
print(ex)
else:
db.commit()
cr.close()
db.close()
python_操作MySQL 初解的更多相关文章
- python_操作MySQL 初解 之__<类方法调用并 增-删-改-查>
文件一: 调用(sqls文件) # 导入模块 import pymysql from sqls import * # 创建类 class KaoShi(object): # 初始化 def __ini ...
- ASP.NET Core 1.0 使用 Dapper 操作 MySql(包含事务)
操作 MySql 数据库使用MySql.Data程序包(MySql 开发,其他第三方可能会有些问题). project.json 代码: { "version": "1. ...
- Python(九) Python 操作 MySQL 之 pysql 与 SQLAchemy
本文针对 Python 操作 MySQL 主要使用的两种方式讲解: 原生模块 pymsql ORM框架 SQLAchemy 本章内容: pymsql 执行 sql 增\删\改\查 语句 pymsql ...
- EF操作MySql
EF的CodeFrist操作MySql的提前准备: 1.安装两个包:MySql.Data和MySql.Data.Entity,在VS中程序包管理器中添加2个包.(备注需要的VS2015,并且EF6支持 ...
- .NET Core 使用Dapper 操作MySQL
MySQL官方驱动:http://www.cnblogs.com/linezero/p/5806814.html .NET Core 使用Dapper 操作MySQL 数据库, .NET Core 使 ...
- asp.net core 1.1 升级后,操作mysql出错的解决办法。
遇到问题 core的版本从1.0升级到1.1,操作mysql数据库,查询数据时遇到MissingMethodException问题,更新.插入操作没有问题. 如果你也遇到这个问题,请参照以下步骤进行升 ...
- 练习:python 操作Mysql 实现登录验证 用户权限管理
python 操作Mysql 实现登录验证 用户权限管理
- Python操作MySQL
本篇对于Python操作MySQL主要使用两种方式: 原生模块 pymsql ORM框架 SQLAchemy pymsql pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb ...
- Python中操作mysql的pymysql模块详解
Python中操作mysql的pymysql模块详解 前言 pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同.但目前pymysql支持python3.x而后者不支持 ...
随机推荐
- C++11 中的强类型枚举
// C++11之前的enum类型是继承C的,不温不火: // C++11对enum动刀了,加强了类型检查,推出强类型enum类型,眼前一亮 // 使用过QT 的都知道,早就应该这么做了,用的很爽!! ...
- [CF666E]Forensic Examination:后缀自动机+线段树合并
分析 用到了两个小套路: 使用线段树合并维护广义后缀自动机的\(right\)集合. 查询\(S[L,R]\)在\(T\)中的出现次数:给\(T\)建SAM,在上面跑\(S\),跑到\(R\)的时候先 ...
- Mysql 实用语句记录
都是工作中遇到的需求,但不是常用sql,特此记录,方便以后使用: 1.将指定列的数据拼起来存到某一列 UPDATE table_name SET b_col_name=CONCAT(b_col_nam ...
- JAVA初级面试题,附个人理解答案
一,面向对象的特征:1.抽象 包括数据抽象跟行为抽象,将对象共同的特征取出形成一个类2.继承 被继承类为基类/超类,继承类为子类/派生类3.封装 多次使用道德数据或方法,封装成类,方便多次重复调用4. ...
- Ubuntu:Unable to locate package ***
在Ubuntu 上使用apt-get 安装包时遇到 Unable to locate package 的信息 解决方案: 更细apt-get然后重新安装 #sudo apt-get update ...
- Kettle使用教程之数据同步
数据模型原型如下: 1.表输入,针对最新的数据输入的表 2.目标表,需要更新的表 3.两个表都需要进行排序操作 4.合并,根据id进行合并 5.数据同步(包括更新.插入.删除) 6.点击运行,就可以实 ...
- 阶段3 2.Spring_02.程序间耦合_7 分析工厂模式中的问题并改造
循环打印 工厂了的打印先注释掉 打印出来了5次对象. 打印数字i同时,让i++操作.为了看他被常见了几次实例 调用保存的方法 没个都想都有一个唯一的实例.在创建对象的时候,重新初始化了i的值.所以i每 ...
- 阶段3 2.Spring_02.程序间耦合_4 曾经代码中的问题分析
创建新的项目 修改打成jar包 创建一个接口 用来模拟保存的方法 创建接口的实现类 我们没有IAccountDao这个类.那么就需要去创建Iaccountdao IAccountDao接口的创建 创建 ...
- 破解root
启动grub按E,进入编辑,ro 改为 rw init=/sysroot/bin/sh然后Ctrl+X进入单用户# chroot /sysroot# passwd root# touch /.auto ...
- harbor扩容
1.参照文档 https://k8s.abcdocker.com/kubernetes_harbor.html 2.设置连接 ln到其他文件目录下