使用pyodbc从Python应用程序将值插入到Access 2003数据库 [英] Inserting values into a Access 2003 database from a Python application using pyodbc

查看:2957
本文介绍了使用pyodbc从Python应用程序将值插入到Access 2003数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经检查过stackoverflow很多过去,总是能够找到我一直在寻找,但我似乎不能得到这个工作,所以我问我的第一个问题。



我不是一个程序员,但我在工作中提到过Python,现在我有一个Python项目。



基本问题:










b $ b

我有一个使用Python和tkinter构建的表单。当按下表单上的按钮时,我想要将值插入到数据库中。



详细信息:



我正在使用Python 3.4,pyodbc和Access 2003数据库。



数据库只是一个名为file_info的表,它有以下字段,字段数据类型列在管道后面。



ID |自动编号



文件名|文字



date |日期/时间



batch_amount |号



parcel_amount |号



sum_amount |数字



最后,我想插入一些在其他函数中计算的值,但目前我只是试图通过一个函数插入一些设置值,我不能



连接字符串:

  db_file = r ''C:\Users\amarquart\Documents\testlockboxdb.mdb'''
user ='admin'
password =''
odbc_conn_str ='DRIVER = {Microsoft访问驱动程序(* .mdb,
* .accdb)}; DBQ =%s; UID =%s; PWD =%s'%\
(db_file,用户,密码)

conn = pyodbc.connect(odbc_conn_str)
cur = conn.cursor()

程序编译和运行良好与此,所以我假设错误不是与连接字符串。下面是一些我在函数中使用的代码示例。

  def insert_data():
sql ='''INSERT INTO file_info

[ID],
[date],
[filename],
[batches_amount],
[parcels_amount],
[sum_amount],

VALUES

'1',
'test',
'8 / 01/2014 1:00:00 PM',
'1',
'1',
'1',
);'''

cur.execute(sql)

conn.commit()
cur.commit()
conn.close()



出现此错误:



Tkinter回调中的异常
Traceback最近调用最后):
调用中的文件C:\Python34\lib\tkinter__init __。py,第1487行
return self.func(* args)
文件C:/ users / amarquart / PycharmProjects / Grid testing / Source / Grid testing.py,行170,在运行
insert_data()
文件C:/ Users / amarquart / PycharmProjects / Grid Testing / Source / Grid testing.py,第36行,在insert_data中
cur.execute(sql)
pyodbc.ProgrammingError:('42000','[42000] ODBC Microsoft Access Driver] INSERT INTO语句中的语法错误。 (-3502)(SQLExecDirectW)')

  def insert_data():
sql =(INSERT INTO [file_info]([ID],[date],[filename],[batches_amount],
[parcels_amount],[sum_amount])
VALUES(?,?,?,?,?,?) ,[1,'8/01/2014 1:00:00 PM','test',10,4,2])
cur.execute(sql)

conn.commit()
cur.commit()
conn.close()

给出此错误:



Tkinter回调中的异常
回溯(最近一次调用)
文件C:\Python34\

文件C:/ Users / amarquart / PycharmProjects / Grid测试/源/网格testing.py,行154,在运行
insert_data()
文件C:/ Users / amarquart / PycharmProjects / Grid testing / Source / Grid testing.py,第20行insert_data
cur.execute(sql)
TypeError:执行的第一个参数必须是字符串或unicode查询。

  def insert_data():
sql =
INSERT INTO file_info(ID,date,filename,batches_amount,parcels_amount,sum_amount)
VALUES(1,'8/01 / 2014 1:00:00 PM','test',2,2,2)

cur.execute(sql)

conn.commit
cur.commit()
conn.close()

错误为最后一个代码

  def insert_data():
cur.execute(INSERT INTO file_info VALUES(AutoNumber, Text,Date / Time,Number,
Number,Number),
(1,'test','8/01/2014 1:00:00 PM',2,2,2)
conn.commit()
cur.commit()
conn.close()


b $ b

产生此错误:



Tkinter回调中的异常
回溯(最近一次调用):
文件C: \\ python34 \lib \tkinter__init __。py,第1487行,调用
return self.func(* args)
文件C:/ Users / amarquart / PycharmProjects / Grid Testing / Source / Grid Testing.py,第153行,运行
insert_data()
文件C:/ Users / amarquart / PycharmProjects /行19,在insert_data
(1,'test','8/01/2014 1:00:00 PM',2,2,2))
pyodbc.ProgrammingError: 0参数标记,但6个参数提供','HY000')



我猜我一直在试图是非常不正确的,所以任何帮助将非常感谢。



感谢大家。



编辑:



基于第一个响应的新尝试,唯一的区别是我使用三重引号,因为代码跨两行

  cur.execute INSERT INTO file_info(ID,date,filename,batches_amount,
parcels_amount,sum_amount)
VALUES(1,'test','8/01/2014 1:00:00 PM',2 ,2,2))
conn.commit()



Tkinter回调中的异常
Traceback(最近一次调用):
文件C:\Python34\lib\tkinter__init __。py ,line 1487, call
return self.func(* args)
文件C:/ Users / amarquart / PycharmProjects / Grid testing / Source / Grid testing.py ,第19行,在insert_data中
VALUES(1,'test','8/01/2014 1:00:00 PM',2,2,2)''')
pyodbc.ProgrammingError :('42000','[42000] [Microsoft] [ODBC Microsoft Access驱动程序] INSERT INTO语句中的语法错误。 (-3502)(SQLExecDirectW)')

  params = [(1,'8/01/2014 1:00:00下午,测试,2,2,2)] 
cur.executemany(插入FILE_INFO(ID,日期,文件名,batch_amount,
parcel_amount,sum_amount)$ b $的b值(?,?,?,?,?,?),params)
conn.commit()

给出此错误



Tkinter回调中的异常
回溯(最近一次调用)
文件C: 。\\Python34\lib\tkinter__init __ PY,1487线,在拨打
返回self.func(*参数)
档C:/用户/ amarquart / PycharmProjects / Grid Testing / Source / Grid testing.py,第20行,insert_data
值(?,?,?,?,?,?),params)
pyodbc.Error: 'HYC00','[HYC00] [Microsoft] [ODBC Microsoft Access Driver]可选功能未实现(106)(SQLBindParameter)')

解决方案

您在几次尝试中接近。日期保留字,用括号括住列名称,并确保列的顺序与值的顺序匹配:

  ... 
sql =
INSERT INTO file_info(ID,[date] filename,batches_amount,parcels_amount,sum_amount)
VALUES(1,'8/01/2014 1:00:00 PM','test',2,2,2)

cur.execute(sql)
....

根据Gord的下面的评论,支持Access的参数化查询,所以理想的代码是:

  .... 
params = ,'8/01/2014 1:00:00 PM','test',2,2,2)
sql =
INSERT INTO file_info(ID,[date],filename, batches_amount,parcels_amount,sum_amount)
值(?,?,?,?,?,?)

cur.execute(SQL,则params)
...


I've checked stackoverflow a lot in the past and have always been able to find what I've been looking for, but I just can't seem to get this one to work so I'm asking my first question.

I'm not really a programmer, but I mentioned Python at work and now I have a Python project. I was actually getting everything figured out alright, but inserting values into a database is throwing me for a loop.

The Basic Problem:

I have a form built using Python and tkinter. When a button on the form is pressed I want values to be inserted into a database.

The Details:

I'm working with Python 3.4, pyodbc, and an Access 2003 database.

The database is just 1 table called file_info and it has the following fields, the fields data type is listed behind the pipe.

ID | AutoNumber

filename | Text

date | Date/Time

batch_amount | Number

parcel_amount | Number

sum_amount | Number

Eventually I'd like to insert some values calculated in other functions, but currently I'm just trying to insert some set values via a function and I can't get it to work.

Connection string:

db_file = r'''C:\Users\amarquart\Documents\testlockboxdb.mdb'''
user = 'admin'
password = ''
odbc_conn_str = 'DRIVER={Microsoft Access Driver (*.mdb,   
*.accdb)};DBQ=%s;UID=%s;PWD=%s' % \
(db_file, user, password)

conn = pyodbc.connect(odbc_conn_str)
cur = conn.cursor()     

The program compiles and runs fine with this so I'm assuming the error isn't with the connection string. So here's some examples of the code I've been using in my function to no avail.

def insert_data():
    sql = '''INSERT INTO file_info
    (
      [ID],
      [date],
      [filename],
      [batches_amount],
      [parcels_amount],
      [sum_amount],
    )
    VALUES
    (
      '1',
      'test',
      '8/01/2014 1:00:00 PM',
      '1',
      '1',
      '1',
    );'''

    cur.execute(sql)

    conn.commit()
    cur.commit()
    conn.close()

That gives this error:

Exception in Tkinter callback Traceback (most recent call last): File "C:\Python34\lib\tkinter__init__.py", line 1487, in call return self.func(*args) File "C:/Users/amarquart/PycharmProjects/Grid testing/Source/Grid testing.py", line 170, in run insert_data() File "C:/Users/amarquart/PycharmProjects/Grid testing/Source/Grid testing.py", line 36, in insert_data cur.execute(sql) pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement. (-3502) (SQLExecDirectW)')

def insert_data():
    sql = ("""INSERT INTO [file_info] ([ID], [date], [filename], [batches_amount],     
         [parcels_amount], [sum_amount])
          VALUES (?, ?, ?, ?, ?, ?)""", [1, '8/01/2014 1:00:00 PM', 'test', 10, 4, 2])
    cur.execute(sql)

    conn.commit()
    cur.commit()
    conn.close()

gives this error:

Exception in Tkinter callback Traceback (most recent call last): File "C:\Python34\lib\tkinter__init__.py", line 1487, in call return self.func(*args) File "C:/Users/amarquart/PycharmProjects/Grid testing/Source/Grid testing.py", line 154, in run insert_data() File "C:/Users/amarquart/PycharmProjects/Grid testing/Source/Grid testing.py", line 20, in insert_data cur.execute(sql) TypeError: The first argument to execute must be a string or unicode query.

def insert_data():
    sql = """
    INSERT INTO file_info (ID, date, filename, batches_amount, parcels_amount, sum_amount)
    VALUES (1, '8/01/2014 1:00:00 PM', 'test', 2, 2, 2)
    """ 
    cur.execute(sql)

    conn.commit()
    cur.commit()
    conn.close()    

Gave the same error as the last code

def insert_data():
   cur.execute("INSERT INTO file_info VALUES (AutoNumber, Text, Date/Time, Number,
               Number, Number)",
(1, 'test', '8/01/2014 1:00:00 PM', 2, 2, 2))
   conn.commit()
   cur.commit()
   conn.close()

Gave this error:

Exception in Tkinter callback Traceback (most recent call last): File "C:\Python34\lib\tkinter__init__.py", line 1487, in call return self.func(*args) File "C:/Users/amarquart/PycharmProjects/Grid testing/Source/Grid testing.py", line 153, in run insert_data() File "C:/Users/amarquart/PycharmProjects/Grid testing/Source/Grid testing.py", line 19, in insert_data (1, 'test', '8/01/2014 1:00:00 PM', 2, 2, 2)) pyodbc.ProgrammingError: ('The SQL contains 0 parameter markers, but 6 parameters were supplied', 'HY000')

I'm guessing everything I've tried is extremely incorrect so any help would be greatly appreciated.

Thanks everyone.

EDIT:

new attempts based on first response, the only difference is that I use triple quotes because the code spans 2 lines

cur.execute("""INSERT INTO file_info (ID, date, filename, batches_amount,   
parcels_amount, sum_amount) 
         VALUES (1, 'test', '8/01/2014 1:00:00 PM', 2, 2, 2)""")
conn.commit()

gives this error

Exception in Tkinter callback Traceback (most recent call last): File "C:\Python34\lib\tkinter__init__.py", line 1487, in call return self.func(*args) File "C:/Users/amarquart/PycharmProjects/Grid testing/Source/Grid testing.py", line 19, in insert_data VALUES (1, 'test', '8/01/2014 1:00:00 PM', 2, 2, 2)''') pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement. (-3502) (SQLExecDirectW)')

params = [(1, '8/01/2014 1:00:00 PM', 'test', 2, 2, 2)]
cur.executemany("""insert into file_info(ID, date, filename, batch_amount,   
parcel_amount, sum_amount)
                values (?, ?, ?, ?, ?, ?)""", params)
conn.commit()

gives this error

Exception in Tkinter callback Traceback (most recent call last): File "C:\Python34\lib\tkinter__init__.py", line 1487, in call return self.func(*args) File "C:/Users/amarquart/PycharmProjects/Grid testing/Source/Grid testing.py", line 20, in insert_data values (?, ?, ?, ?, ?, ?)""", params) pyodbc.Error: ('HYC00', '[HYC00] [Microsoft][ODBC Microsoft Access Driver]Optional feature not implemented (106) (SQLBindParameter)')

解决方案

You were close on a couple attempts. Date is a reserved word in Access, surround the column name with brackets and ensure the order of columns matches the order of values:

...
sql = """
INSERT INTO file_info (ID, [date], filename, batches_amount, parcels_amount, sum_amount)
VALUES (1, '8/01/2014 1:00:00 PM', 'test', 2, 2, 2)
""" 
cur.execute(sql)
....

According to Gord's comments below, parameterized queries are supported against Access, so the ideal code would be:

....
params = (1, '8/01/2014 1:00:00 PM', 'test', 2, 2, 2)
sql = """
INSERT INTO file_info (ID, [date], filename, batches_amount, parcels_amount, sum_amount)
VALUES (?, ?, ?, ?, ?, ?)
""" 
cur.execute(sql, params)
...

这篇关于使用pyodbc从Python应用程序将值插入到Access 2003数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆