基于python的pymysql模块实现向数据库中插入一条数据
基于业务需求需要向某表经常插入数据,故编辑了该脚本方便在堡垒机中直接向服务器插入数据,这里我们以一行为例。
程序介绍:
程序分为两个函数分别为插入函数和查询函数顾名思义就是实现数据插入和查询
效果:带参数执行该程序 程序会判断该表中是否存在该数据,如果有则返回该数据已经存在,如果不存在则插入该数据;
效果如图
具体实现:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2018-07-16 16:09:41
# @Author : Zhou jiaan
# @Version : $1.0
# filename : insert_Merid.py
import os
import re
import sys
import pymysql
def insert_merid(merid):
conn = pymysql.connect(host="10.1.11.37", port=3306, user="root", passwd="password", db="test",
charset="urf8mb4")
cur = conn.cursor()
cur.execute(
"INSERT INTO merid_invoice(id,merid,chtype,Isinvoice)VALUES(NULL,{},9,1);".format(merid))
conn.commit()
conn.close()
def select_merid(merid):
conn = pymysql.connect(host="10.1.11.37", port=3306, user="root", passwd="password", db="test",
charset="urf8mb4")
cur = conn.cursor()
cur.execute(
"select * from merid_invoice where merid={} ;".format(merid))
merid_result = cur.fetchall()
print(merid_result)
# print(merid_result==())
conn.close()
if merid_result == ():
insert_merid(merid)
print("你需要的merid已经插入merid_invoice表")
conn = pymysql.connect(host="10.1.11.37", port=3306, user="root", passwd="password", db="test",
charset="utf8")
cur = conn.cursor()
cur.execute(
"select * from merid_invoice where merid={} ;".format(merid))
merid_result = cur.fetchall()
print(merid_result)
conn.close()
else:
print("你输入的merid已经存在:请核对后重新执行该程序")
# conn.close()
def main():
try:
merid_num = sys.argv[1]
except Exception as e:
merid_num = input("请输入十位有效数字:")
else:
print("输出merid_num:{}".format(merid_num))
finally:
merid = merid_num
select_merid(merid)
if __name__ == '__main__':
main()
原文地址 https://blog.csdn.net/sinat_34789167/article/details/81111425