Python利用Psycopg2模塊將Excel表格數據導入Postgressql


1 切記踩坑點

error_tup = () 應該為元組,而不是字典

因為字典的value是可變類型,for循環時,列表添加字典時,如果在for 循環中對字典的值進行修改,此時列表中添加的所有的字典的值都被修改成相同的值了,即字典的值的地址可以修改,故把列表中所有的字典的值修改了,所以要用元祖不可變類型的值來替換字典。

此時的結構應該是[(),(),(),()...]

 

 

 

 

 

 1 import xlrd
 2 import psycopg2
 3 import redis
 4 conn = redis.Redis(host='localhost', port=6379)
 5 pipe = conn.pipeline()
 6 def check_data():
 7     book = xlrd.open_workbook('test.xlsx')
 8     sheet = book.sheet_by_name("Sheet1")
 9     conn = psycopg2.connect(dbname="ggg",
10                             user='postgres',
11                             password='521314',
12                             host="localhost",
13                             port=5432)
14     count = 0
15     cur = conn.cursor()
16     error_tup = ()
17     error_list = []
18     for r in range(1, sheet.nrows):
19         name = sheet.cell(r, 0).value
20         email = sheet.cell(r, 1).value
21         data = (re.match(r'^[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+){0,4}@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+){0,4}$', email)) and 1 or 0
22         if not ((email and data) and name):
23             count += 1
24             error_tup = (name, email)
25             error_list.append(error_tup)
26             continue
27         pipe.hset('name', name, email)
28     if not count:
29         values = []
30         for i in pipe.hget("name", name).command_stack:
31             try:
32                 value = (i[0][2], i[0][3])
33                 values.append(value)
34             except Exception:
35                 pass
36         query = "insert into users_employees (name, email) values(%s,%s);"
37         # 批量提交數據 單條數據提交用cur.execute(query, value)
38         cur.executemany(query, values)
39         conn.commit()
40         values.clear()
41         conn.close()
42         cur.close()
43         columns = str(sheet.ncols)
44         rows = str(sheet.nrows)
45         print("{}行數據錯誤".format(count))
46         print("導入" + columns + "" + rows + "行數據到pgsql數據庫!!!")
47         return "{}行數據錯誤".format(count)
48     print(error_list[:20])
49     return error_list[:20]
50 
51 
52 if __name__ == '__main__':
53     check_data()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM