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的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程