The implementation of pymysql module based on python to insert a piece of data into the database

Based on the business requirements, data is often inserted into a table, so the script is edited to insert data directly into the server in the bastion machine. Here we take a behavior example.

Program introduction:
The program is divided into two functions: insert function and query function. As the name implies, it implements data insertion and query

Effect: executing the program with parameters will determine whether the data exists in the table. If yes, the data already exists will be returned. If no, the data will be inserted;

The effect is as follows

Specific implementation:

#!/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("What you need merid Already inserted merid_invoice surface")
        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("What you entered merid Already exists: please check and execute the program again")


#    conn.close()


def main():
    try:
        merid_num = sys.argv[1]
    except Exception as e:
        merid_num = input("Please enter ten valid digits:")
    else:
        print("output merid_num:{}".format(merid_num))
    finally:
        merid = merid_num
        select_merid(merid)


if __name__ == '__main__':
    main()

Tags: Python

Posted on Sun, 09 Feb 2020 11:59:49 -0800 by shawjames