Копирование строки из одной базы данных в другую и изменение некоторых значений

0

Я пытаюсь скопировать строку с одного сервера базы данных на другой и затем присвоить разные значения некоторым полям.

prod_conn = pymysql.connect(prod_common_db_endpoint, prod_user, prod_password, prod_common_table_name)

prod_cursor = prod_conn.cursor()


prod_ConnectFirm_table = prod_cursor.execute("select * from beta2_Common.Firm where id = " + prod_source_firm + ";")
data = prod_cursor.fetchall()
for row in data:
    oef_name = row[1]
    oef_path = row[2]
    oef_username = row[5]
    oef_password = row[6]
    oef_poolLimit = row[7]
    oef_database = row[8]
    oef_port = row[9]
    oef_serverGroupId = row[10]
    oef_threadWeight = row[11]
    oef_isDeleted = row[12]
    oef_tags = row[13]
    oef_createdBy = row[14]
    oef_createdDate = row[15]
    oef_editedBy = row[16]
    oef_editedDate = row[17]

    if env == "dev":
        oef_server = 'dev-firmdb1-cluster.cluster-xxxxxxxxxxx.us-east-1.rds.amazonaws.com'
        oef_roServer = 'dev-firmdb1-cluster.cluster-ro-xxxxxxxxxxx.us-east-1.rds.amazonaws.com'
    elif env == "beta":
        oef_server = 'beta-cluster.cluster-xxxxxxxxxxx.us-east-1.rds.amazonaws.com'
        oef_roServer = 'beta-cluster.cluster-ro-xxxxxxxxxxx.us-east-1.rds.amazonaws.com'


conn = pymysql.connect(target_common_db_endpoint, user, password, common_schema_name)

cursor = conn.cursor()


add_Firm_command = ("INSERT INTO Common.Firm "
            "(id, name, path, server, roServer, username, password, poolLimit, database, port, serverGroupId, threadWeight, \
            isDeleted, tags, createdBy, createdDate, editedBy, editedDate) "
            "VALUES (%(oef_last_id)s, %(oef_name)s, %(oef_path)s, %(oef_server)s, %(oef_roServer)s, %(oef_username)s, %(oef_password)s, \
            %(oef_poolLimit)s, %(oef_database)s, %(oef_port)s, %(oef_serverGroupId)s, %(oef_threadWeight)s, %(oef_isDeleted)s, %(oef_tags)s, \
            %(oef_createdBy)s, %(oef_createdDate)s, %(oef_editedBy)s, %(oef_editedDate)s)")
oef_last_id = conn.insert_id()

Firm_values = {
    'oef_last_id' : oef_last_id,
    'oef_name' : oef_name,
    'oef_path' : oef_path,
    'oef_server' : oef_server,
    'oef_roServer' : oef_roServer,
    'oef_username' : oef_username,
    'oef_password' : oef_password,
    'oef_poolLimit' : oef_poolLimit,
    'oef_database' : oef_database,
    'oef_port' : oef_port,
    'oef_serverGroupId' : oef_serverGroupId,
    'oef_threadWeight' : oef_threadWeight,
    'oef_isDeleted' : oef_isDeleted,
    'oef_tags' : oef_tags,
    'oef_createdBy' : oef_createdBy,
    'oef_createdDate' : oef_createdDate,
    'oef_editedBy' : oef_editedBy,
    'oef_editedDate' : oef_editedDate
}


cursor.execute(add_Firm_command, Firm_values)

conn.commit()
cursor.close()
conn.close()
conn.rollback()
print("error inserting")

и я получаю сообщение об ошибке "У вас есть ошибка в синтаксисе SQL, проверьте руководство, соответствующее версии вашего сервера MySQL, для правильного синтаксиса для использования рядом с" database, port, serverGroupId, threadWeight "в строке 1"):

    Traceback (most recent call last):
  File "sql_test_4_a.py", line 264, in <module>
    cursor.execute(add_orionEclipseFirm_command, orionEclipseFirm_values)
  File "/usr/local/lib/python3.6/site-packages/pymysql/cursors.py", line 170, in execute
    result = self._query(query)
  File "/usr/local/lib/python3.6/site-packages/pymysql/cursors.py", line 328, in _query
    conn.query(q)
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 516, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 727, in _read_query_result
    result.read()
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1066, in read
    first_packet = self.connection._read_packet()
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 683, in _read_packet
    packet.check_error()
  File "/usr/local/lib/python3.6/site-packages/pymysql/protocol.py", line 220, in check_error
    err.raise_mysql_exception(self._data)
  File "/usr/local/lib/python3.6/site-packages/pymysql/err.py", line 109, in raise_mysql_exception
    raise errorclass(errno, errval)
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'database,             port,             serverGroupId,             threadWeight,' at line 1")

любая идея, как исправить эту ошибку?

Теги:
pymysql

1 ответ

0

Драйвер базы данных сообщает вам, что

рядом с базой данных, портом, serverGroupId, threadWeight, '

Рассматривая инструкцию SQL, вы включаете обратную косую черту - предположительно для продолжения строки - внутри строки оператора.

Вам не нужны эти персонажи. Вы можете заключить оператор в круглые скобки, как вы уже сделали, и сделать каждую строку инструкции отдельной строкой. Интерпретатор python автоматически свяжет их. Вам нужно будет оставить пробел в конце каждой строки, чтобы избежать объединения отдельных слов.

Например:

>>> s = ("foo"
...      "bar")
>>> s
'foobar'    # <- words concatenated
>>> s = ("foo "
...      "bar")
>>> s
'foo bar'   # <- words separated

Таким образом, ваш код должен выглядеть так:

add_Firm_command = ("INSERT INTO Common.Firm "
            "(id, name, path, server, roServer, username, password, poolLimit, database, port, serverGroupId, threadWeight, "
            "isDeleted, tags, createdBy, createdDate, editedBy, editedDate) "
            "VALUES (%(oef_last_id)s, %(oef_name)s, %(oef_path)s, %(oef_server)s, %(oef_roServer)s, %(oef_username)s, %(oef_password)s, "
            "%(oef_poolLimit)s, %(oef_database)s, %(oef_port)s, %(oef_serverGroupId)s, %(oef_threadWeight)s, %(oef_isDeleted)s, %(oef_tags)s, "
            "%(oef_createdBy)s, %(oef_createdDate)s, %(oef_editedBy)s, %(oef_editedDate)s)")

Ещё вопросы

Сообщество Overcoder
Наверх
Меню