成功打开连接后插入数据时出错

时间:2015-04-20 07:45:46

标签: database

我将数据从mysql表插入postgres表,我的代码是:

from sqlalchemy import create_engine, MetaData, Table

from sqlalchemy.orm import mapper, sessionmaker

import psycopg2

class TestTable(object):

    pass

class StoreTV(object):

    pass

if __name__ == "__main__":

    engine = create_engine('mysql://root@localhost:3306/irt', echo=False)

    Session = sessionmaker(bind=engine)
    session = Session()

    metadata = MetaData(engine)
    test_table = Table('test_1', metadata, autoload=True)

    store_tv_table = Table('roku_store', metadata, autoload=True)

    mapper(TestTable, test_table)
    mapper(StoreTV, store_tv_table)

    res = session.query(TestTable).all()
    print res[1].test_1col

    tv_list = session.query(StoreTV).all()

    for tv in tv_list:
        tv_data = dict()
        tv_data = {
            'title': tv.name,
            'email': tv.business_email
        }
        print tv_data


        conn = psycopg2.connect(database="db", user="user", password="pass", host="localhost", port="5432")
        print "Opened database successfully"
        cur = conn.cursor()
        values = cur.execute("Select * FROM iris_store")
        print values
        cur.execute("INSERT INTO iris_store(title, business_email) VALUES ('title':tv_data[title], 'business_email':tv_data[business_email])")
        print "Record created successfully"

        conn.commit()
        conn.close()

我无法从postgres数据中获取数据并插入postgres表 虽然我成功从Mysql表中获取数据

错误是:

  

东西

     

{' email':' name@example.com',' title':" some name"}

     

成功打开数据库

     

     

追踪(最近一次呼叫最后一次):

     

文件" /home/Desktop/porting.py" ;,第49行,in      cur.execute(" INSERT INTO iris_store(title,business_email)VALUES(' title':tv_data [title],' business_email':tv_data [business_email])" )

     

psycopg2.ProgrammingError:语法错误在或附近":"   第1行:... iris_store(title,business_email)VALUES('标题':tv_data [t ...                                                               ^

2 个答案:

答案 0 :(得分:0)

您的主要问题是您在插入查询中遇到了sql语法错误。看起来应该是这样的:

cur.execute("INSERT INTO iris_store(title, business_email) VALUES (%(title)s, %(email)s)", tv_data)

供参考,请参阅:Passing parameters to SQL queries

另外,您可能不希望为tv_list中的每个值创建与postgres数据库的新连接,您应该在for循环之外移动连接和关闭调用,并且每次打印整个表格似乎也不是很有用

答案 1 :(得分:0)

乌斯曼 您必须检查电子邮件的数据类型以插入数据。 因为要将数据从mysql插入postgres,你必须同时使用两个相同类型的字段。 click here and page no 28 will describe you aboout the data types of mysql and postgres