将数据从文件插入数据库

时间:2012-12-07 13:53:00

标签: python pyodbc

我有一个包含多个插入语句(1000 +)的.sql文件,我想将此文件中的语句运行到我的Oracle数据库中。

现在,我使用带有odbc的python连接到我的数据库,其中包含以下内容:

import pyodbc
from ConfigParser import SafeConfigParser

def db_call(self, cfgFile, sql):

    parser = SafeConfigParser()
    parser.read(cfgFile)
    dsn = parser.get('odbc', 'dsn')
    uid = parser.get('odbc', 'user')
    pwd = parser.get('odbc', 'pass')

    try:
        con = pyodbc.connect('DSN=' + dsn + ';PWD=' + pwd + ';UID=' + pwd)
        cur = con.cursor()
        cur.execute(sql)
        con.commit()

    except pyodbc.DatabaseError, e:
            print 'Error %s' % e
            sys.exit(1)

    finally:

        if con and cur:
            cur.close()
            con.close()

with open('theFile.sql','r') as f:
    cfgFile = 'c:\\dbinfo\\connectionInfo.cfg'
    #here goes the code to insert the contents into the database using db_call_many       
    statements = f.read()
    db_call(cfgFile,statements)

但是当我运行它时,我收到以下错误:

pyodbc.Error: ('HY000', '[HY000] [Oracle][ODBC][Ora]ORA-00911: invalid character\n (911) (SQLExecDirectW)')

但该文件的所有内容仅为:

INSERT INTO table (movie,genre) VALUES ('moviename','horror');

修改

在db_db_call(cfgFile,statements)之前添加print '<{}>'.format(statements)我得到结果(100 +):

<INSERT INTO table (movie,genre) VALUES ('moviename','horror');INSERT INTO table (movie,genre) VALUES ('moviename_b','horror');INSERT INTO table (movie,genre) VALUES ('moviename_c','horror');>

感谢您抽出时间阅读本文。

2 个答案:

答案 0 :(得分:1)

现在有点澄清 - 你有很多单独的SQL语句,例如INSERT INTO table (movie,genre) VALUES ('moviename','horror');

然后,你有效地在cur.executescript()之后比当前状态(我不知道pyodbc是否支持DB API的那部分,但是任何原因,你不能只执行执行到数据库本身?

答案 1 :(得分:0)

使用read()函数读取文件时,也会读取文件末尾的结束行(\ n)。我认为你应该使用db_call(cfgFile,statements [: - 1])来消除结束行。

相关问题