2015-12-23 96 views
1

我有兩臺機器:local_machine,server_machine。我在local_machine的server_machine和sftp服務器上有mysql服務器。我正嘗試使用python將sritest.csv文件(UTF-8)從local_machine發送到server_machine。這些都是sritest.csv內容: 1,2,3python-mysql cursor.execute失敗,訪問被拒絕錯誤

我已經在SQL查詢保存在sritest.sql而這些文件的內容:

LOAD DATA INFILE '{}' 
INTO TABLE TESTBED_STAGING.test 
COLUMNS TERMINATED BY ',' 
; 

這是Python腳本我現在有:

import MySQLdb 
import os 
import string 

# Open database connection 
db = MySQLdb.connect (host="1.2.3.4",port=3306,user="app_1",\ 
         passwd="passwd",db="TESTBED_STAGING") 

cursor=db.cursor() 
#Query under testing 
sql = open('sritest.sql','r').read() 
print sql 
l = os.listdir(".") 
for file_name in l: 
    if file_name.endswith('sritest.csv'): 
     print 'the csv file we are reading is: '+file_name 
     #try: 
     cursor = db.cursor() 
     print 'filename is '+sql.format(file_name) 
     cursor.execute(sql.format(file_name)) 
     db.commit() 
     ''' 
     except Exception: 
      # Rollback in case there is any error 
      db.rollback() 
      print 'ERROR - So, rollback :(:(' 
     ''' 
# disconnect from server 
db.close() 

在上面的腳本中,我評論tryexcept這樣我就可以看到錯誤的地方休息。目前,該代碼在cursor.execute(sql.format(file_name))斷行,出現此錯誤:

OperationalError: (1045, "Access denied for user 'app_1'@'%' (using password: YES)") 

我一直在玩周圍,但沒有能夠解決它。任何建議/想法?

回答

1

對於初學者來說,在每個循環創建光標是不是一個好主意。您之前已經創建了一個遊標,因此您可以在for循環中刪除遊標聲明。

其次,我認爲你的錯誤是由於缺乏在1.2.3.4 MySQL服務器上遠程訪問用戶使用的app_1。試試這個服務器的MySQL的控制檯上,

GRANT ALL PRIVILEGES ON TESTBED_STAGING.* TO 'app_1'@'%'; 

最後,儘量避免使用print "line"符號,並開始切換到print("line")符號的兼容性與Python 3.x的

+0

'app_1'用戶已經擁有的MySQL服務器(我的意思是,我跑在上面的命令已經)上的所有特權。 –

0

我想出答案,並決定離開這個問題打開那些誰可能面臨類似的問題:

  1. 在MySQL服務器(server_machine),確保你這樣做,你啓動mysql後: mysql>grant all privileges on *.* to 'app_1'@'%' identified by 'passwd';
  2. 變化LOAD DATA INFILE '{}'sritest.sqlLOAD DATA LOCAL INFILE '{}'
  3. 在Python代碼,編輯MySQLdb.connect語句: db = MySQLdb.connect (host="1.2.3.4",port=3306,user="app_1",\ passwd="passwd",db="TESTBED_STAGING", local_infile=1)

所有錯誤都消除數據傳輸。