您好,登錄后才能下訂單哦!
如下所示:
#-*- encoding:utf-8 -*- import csv import sys,os import pymysql def read_csv(filename): ''' 讀取csv文件 ''' data = [] with open(filename) as f: f_csv = csv.reader(f) headers = next(f_csv) #數據格式[1111,22222,1111,1111,.....] for row in f_csv: # Process row field1=row[0] data.append(row) print headers return data def load_data(): ''' 插入數據庫 ''' filename = sys.argv[1] try: #獲取一個數據庫連接,注意如果是UTF-8類型的,需要制定數據庫 conn=pymysql.connect(host='192.168.1.161',user='naliworld',passwd='password!',db='search',port=3306,charset='utf8') cur=conn.cursor()#獲取一個游標 data=read_csv(filename) for row in data: # Process row field1=row[0] sql='''insert into search.tb_text_uid_list(appId,type,uid,creator,createTime) values({},{},{},{},{}) '''.format(3,1,field1,'\'admin\'','\'2018-08-14 13:44:09\'') print sql cur.execute(sql) cur.close()#關閉游標 conn.commit() conn.close()#釋放數據庫資源 except Exception as e :print(e) def get_sql(): ''' 插入數據庫生成插入sql ''' sql_list = [] filename = sys.argv[1] data=read_csv(filename) for row in data: # Process row field1=row[0] sql='''replace into search.tb_text_uid_list(appId,type,uid,creator,createTime) values({},{},{},{},{}) '''.format(3,1,field1,'\'admin\'','\'2018-08-14 13:44:09\'') sql_list.append(sql) file_object = open('sql.txt', 'w') file_object.writelines([line+';\n' for line in sql_list]) file_object.close( ) if __name__ == "__main__": get_sql()
以上這篇對python插入數據庫和生成插入sql的示例講解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。