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操作数据库


下一篇:(pyCharm)pymssql远程连接sql server以及相关语法介绍