Python 調取MYSQL資料並插入到CSV檔案

來源:互聯網
上載者:User


如何利用python指令碼將遠端資料庫查詢值,並將該值按照csv中"column A"對應關係整體插入到"column B",最近handle了一個case,聯想到python天生對資料處理較shell有明顯的優勢,最後嘗試用指令碼搞定這個看起來邏輯很簡單,但又不簡單的data processing.
Target:
column A 是DB記憶體儲的若干Project name,需要通過查詢資料庫,擷取這些project name在DB對應的Project key的具體值,並插入column A後儲存.

#!/usr/bin/env python# encoding: utf-8import MySQLdbimport csvimport sys# Define csv listCsv_content = []Csv_content_edited = []# Define project listProject_names = []# Define db listDb_content = []# Define the file that needs to be handled.try: file_name = sys.argv[1] new_file_name = file_name.split('.')[0] + '_new.' + file_name.split('.')[1]except IndexError: passdef selectDB(): # Open db connection db = MySQLdb.connect("test.com", "testuser", "testuser", "testdb") # Use cursor() fuction to get current db cursor cursor = db.cursor() Csv_content_edited = readContent(file_name) for c in range(1,len(Csv_content_edited)):  Project_names.append(Csv_content_edited[c][0]) Project_name_string = ",".join(['"' + p + '"' for p in Project_names]) # SQL "SELECT" statement sql = 'select pname,pkey from project where pname in (%s)' %Project_name_string  try:  # Execute SQL  cursor.execute(sql)  # Obtain all the record list  results = cursor.fetchall()  for row in results:   #lower_user_name = row[3]   Db_content.append(row)  return Db_content except:  print "Error: unable to fecth data" # Close connection db.close()def readContent(file_name): # Read the csv file,then put it into list. with open(file_name, 'r') as csvfile:  csv_reader = csv.reader(csvfile, delimiter=',')  for row in csv_reader:       if row[0]:    Csv_content.append(row) return Csv_contentdef insert_col(): Csv_content_edited = readContent(file_name) # Insert null value to each components of "Csv_content_edited" afterward. for i in range(0,len(Csv_content_edited)):  Csv_content_edited[i].insert(1,'') # Define the second inserted column title. Csv_content_edited[0][1] = "Pkey" # Grab the users data from db. Db_content = selectDB() # print Db_content  for d in range(0,len(Db_content)):  Pkey = Db_content[d][1]  Pname = Db_content[d][0]  for c in range(0,len(Csv_content_edited)):     if Csv_content_edited[c][0] == Pname:    Csv_content_edited[c][1] = Pkey # print Csv_content_edited pname_list = [] Csv_content_edited_new = []  for c in range(0,len(Csv_content_edited)):  if not Csv_content_edited[c][0] in pname_list:   pname_list.append(Csv_content_edited[c][0])   Csv_content_edited_new.append(Csv_content_edited[c]) # print Csv_content_edited_new  return Csv_content_edited_new # Write the csv file. def writeContent(): with open(new_file_name,'wb') as csvfile:  csv_writer = csv.writer(csvfile)  csv_writer.writerows(insert_col())# Execute the finnal function. if __name__ == '__main__': try:  writeContent() except (IOError,NameError,IndexError):  print "Please type the correct file name. e.g: '" + sys.argv[0] + " testfile.csv'" else:  print 'The result file is: %s' %new_file_name

Result:

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.