python建表写入数据库简单demo


#python建表写入数据库  --示例demo

import requests
import re
import pymysql

def printgoods(itl):
    tplt = "{:2}\t{:2}\t{:2}\t{:2}\t{:2}"
    print(tplt.format("ZH_NAME", "CGI", "scan_start_time","region_name","vendor_id"))

    count = 0
    conn = pymysql.connect(host='127.0.0.1', user='root', password='123456', db='test',charset="utf8")
    cur = conn.cursor()

	c = '''
                drop table if exists coffe;
                '''

    try:
        cur.execute(c)
        conn.commit()
        print('成功')
    except:
         print("错误")

    sqlc = '''
                create table coffe(
                id int(11) not null auto_increment primary key,
                name varchar(255) ,
                price float ,
                time varchar(255),
                date varchar(255)
                )DEFAULT CHARSET=utf8;
               
                '''
    try:
        cur.execute(sqlc)
        conn.commit()
        print('成功')
    except:
         print("错误")

    save_path = 'D:/test.txt'
    f=open(save_path,'a')
    for g in itl:
        count = count + 1
        print(count)
        print(g[0])
        print(g[1])
        b=tplt.format(count, g[0], g[1],g[2],g[3])

        sqla = '''
        insert into  coffe(name,price,time,date)
        values(%s,%s,%s,%s);
       '''
        try:
            cur.execute(sqla,(g[1],g[0],g[2],g[3]))
            conn.commit()
            print('成功')
        except:
            print("错误")

        f.write(b + '\n')

    f.close()
    conn.commit()
    cur.close()
    conn.close()


def main():
    itl = [["156",45],["23明确67",234567],["345678",345678],["456789",456789]]

    itl = [["2324",8,"2","yufei眼"],["34436",234567,"34",""],["345678",345678,"臣",""],["456789",456789,"yan",""]]
   
    print(printgoods(itl))


main()

猜你喜欢

转载自blog.csdn.net/wangyan_z/article/details/81190844
今日推荐