python操作mysql
2021/7/21 2:09:05
本文主要是介绍python操作mysql,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
import pymysql
def insertOne(result):
# 连接数据库
db = pymysql.Connect(
host='121.196.103.249',
port=33306,
user='root',
passwd='123456',
db='spider',
charset='utf8'
)
# 获取游标 cursor = db.cursor() try: # 插入数据 sql = """insert into test(name,age) values (%s,%s) """ cursor.execute(sql, (result["name"], result["age"])) except: print("异常") # 关闭连接 db.commit() cursor.close() db.close()
def insertMany(result):
# 连接数据库
db = pymysql.Connect(
host='121.196.103.249',
port=33306,
user='root',
passwd='123456',
db='spider',
charset='utf8'
)
# 获取游标 cursor = db.cursor() try: # 插入多条数据 方式一 # sql = """insert into test(age,name) values (%s,%s) """ # data=((x["name"],x["age"]) for x in result) # cursor.executemany(sql,data) # 插入多条数据 方式二 sql = """insert into test(age,name) values (%s,%s) """ for x in result: cursor.execute(sql, (x["name"], x["age"])) except: print("数据库异常") # 关闭连接 db.commit() cursor.close() db.close()
def select():
# 连接数据库
db = pymysql.Connect(
host='121.196.103.249',
port=33306,
user='root',
passwd='123456',
db='spider',
charset='utf8'
)
# 获取游标 cursor = db.cursor() try: sql = "select * from test" cursor.execute(sql) # 获取所有记录列表 results = cursor.fetchall() except: print("异常") db.close() return results
def update(result):
# 连接数据库
db = pymysql.Connect(
host='121.196.103.249',
port=33306,
user='root',
passwd='123456',
db='spider',
charset='utf8'
)
# 获取游标 cursor = db.cursor() try: sql = """UPDATE test set age=%s where name=%s""" data=(result["age"],result["name"]) cursor.execute(sql,data) except: print("异常") # 关闭连接 db.commit() cursor.close() db.close()
if name == 'main':
# result={"name":"haha","age":"18"}
# insertOne(result)
# print("插入成功")
# result=[{"name":"haha","age":"18"},{"name":"haha2","age":"19"}] # insertMany(result) # print("插入成功") result={"name":"haha","age":"100"} update(result) # result=select() # print(1)
这篇关于python操作mysql的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-04部署MySQL集群项目实战:新手入门教程
- 2024-11-04如何部署MySQL集群资料:新手入门指南
- 2024-11-02MySQL集群项目实战:新手入门指南
- 2024-11-02初学者指南:部署MySQL集群资料
- 2024-11-01部署MySQL集群教程:新手入门指南
- 2024-11-01如何部署MySQL集群:新手入门教程
- 2024-11-01部署MySQL集群学习:新手入门教程
- 2024-11-01部署MySQL集群入门:新手必读指南
- 2024-10-23BinLog入门:新手必读的MySQL二进制日志指南
- 2024-10-23Binlog入门:MySQL数据库的日志管理指南