2014-09-23 3 views
1

하나의 테이블을 다른 mysql db로 복사하는 파이썬 코드를 작성하고 있습니다.테이블에서 다른 테이블로 행을 복사하는 중 오류가 발생했습니다.

먼저 'NULL'로 변환해야하는 '없음'으로 null, 빈 값을 읽는 것과 같은 몇 가지 문제가 발생했습니다. I는 연속 인쇄시

pymysql.err.InternalError: (1630, u"FUNCTION datetime.datetime does not exist. 
Check the 'Function Name Parsing and Resolution' section in the Reference Manual") 

내가 datetime.datetime (2014, 8, 25, 8, 24, 51)의 항목을 볼 수있다 -

이제 다음 에러를 도시. datetime.datetime을 datetime.time ( http://pymotw.com/2/datetime/)로 대체하여이 문제를 해결하려고했지만 실패했습니다. 다음과 같이

내 코드는 다음과 같습니다

import re 
from db import conn_main ### database from where to copy 
from db import conn ### database where to copy 
import datetime 

curr1 = conn_main.cursor() 
curr2 = conn.cursor() 

query = 'SELECT * FROM mytable limit 10' 
curr1.execute(query) 
for row in curr1: 
    if row[0] is None or not row[0]: 
      print "error: empty row",row[0] 
      continue 
    else: 
      print "ROW - %s\n" % str(row) 
      row = re.sub('None','NULL',str(row)) 
      query = 'replace into mytable values ' + str(row) 
      curr2.execute(query) 

curr2.commit() 
curr1.close() 
curr2.close() 

역 추적 & 출력 행 :

ROW - (1, '501733938','[email protected]', None, 'https://www.facebook.com/xyz', 
None, None, None, None, None, '2014-08-10T06:06:33+0000', None, 'xyz', None, 
datetime.datetime(2014, 8, 25, 8, 24, 51), None, None, None, None, None, None, None, 
None, None, None, None, None, None, None, None, None) 

Traceback (most recent call last): 
    File "MY_PYTHON_CODE_FILE_PATH", line 390, in <module> curr2.execute(query) 
    File "/usr/local/lib/python2.7/dist-packages/pymysql/cursors.py", line 132, in execute result = self._query(query) 
    File "/usr/local/lib/python2.7/dist-packages/pymysql/cursors.py", line 271, in _query conn.query(q) 
    File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 726, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) 
    File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 861, in _read_query_result result.read() 
    File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 1064, in read first_packet = self.connection._read_packet() 
    File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 826, in _read_packet packet.check_error() 
    File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 370, in check_error raise_mysql_exception(self._data) 
    File "/usr/local/lib/python2.7/dist-packages/pymysql/err.py", line 116, in raise_mysql_exception _check_mysql_exception(errinfo) 
    File "/usr/local/lib/python2.7/dist-packages/pymysql/err.py", line 112, in _check_mysql_exception raise InternalError(errno, errorvalue) 

사람이 오류를 제거 ... 또는 하나의 데이터베이스에서 테이블을 복사 할 다른 더 좋은 방법을 제안 도와 드릴까요 다른 파이썬으로.

+0

전체 추적을 제공 하시겠습니까? – Nilesh

+0

'행 [0]이 '없음'이면 충분하지 않습니까? ''row [0]'의 약자는 무엇입니까? 또한'row [0] == None'을 시도 했습니까? –

+0

@Lafada가 추적을 추가했습니다 – user2952821

답변

1

문제는 some_object의 파이썬 문자열 표현을 SQL로 사용하려고하는 것입니다. 그건 틀렸어요. str(datetime) 모양은datetime.datetime(year, month, day, hour, minute, seconds, milliseconds)

입니다. 올바른 SQL 문자열이 아닙니다.

row[dt_index] = row[dt_index].isoformat() 

또는 콘크리트 형식의 데이터베이스는 예를 들어, 받아 들인다 :이 열 번호가 무엇인지 알고있는 경우 ,이 같은 문자열 값으로 대체 할 수

row[dt_index] = row[dt_index].strftime('%Y-%m-%d %H:%M:%S') 

하지만 몇 가지를 사용하는 것이 좋습니다 라이브러리 또는 매개 변수화 된 쿼리. SQL을 그런 식으로 구축하는 것은 매우 좋지 않으며 안전하지 않은 솔루션입니다.

2

최대 5.7까지의 MySQL 매뉴얼에 따르면 DATETIME (datetime TYPE이 있더라도)이나 패키지 지원 (datetime. *)도 없습니다. 난 소스 데이터베이스에서 datetime의 이진 표현에서 datetime.datetime을 생성하는 python str이라고 가정합니다.