简体   繁体   English

通过VBA MS-ACCESS在PostgreSQL数据库中插入值

[英]Insert values in PostgreSQL database from VBA MS-ACCESS

I've seen this topic before How to insert values into the database table using VBA in MS access But it didn't solve my issue. 如何在MS Access中使用VBA将值插入数据库表之前,我已经看过本主题,但是它并不能解决我的问题。 I'm creating a form to insert values into a table in postgresql that contains arrays [] text. 我正在创建一个表单,将值插入到包含数组[]文本的postgresql表中。 The user must select the items to add and then execute the SQL statement by clicking a button. 用户必须选择要添加的项目,然后通过单击按钮执行SQL语句。 So I first create a button and a text box to load the items to add into the array, here is the code 所以我首先创建一个按钮和一个文本框来加载要添加到数组中的项目,这是代码

Private Sub cmdSig_Click()
 Dim registros As String
 registros = "'" & [memo] & "'" & ", "
 [resu] = registros & [resu]
End Sub

Then I create the button to execute the SQL INSERT INTO statement. 然后,我创建按钮以执行SQL INSERT INTO语句。 Here is the code: 这是代码:

    Private Sub cmdPruebas_Click()
    Dim strsql As String, resultado As String, salida As String

        Dim db As Database
        dbconnect = "ODBC;DRIVER=PostgreSQL ANSI;UID=***;PWD=***;PORT=5432;SERVER=***.***.**.**;DATABASE=somedb;DSN=C:\***"
        Set db = OpenDatabase("", False, False, dbconnect)
        resultado = [resu]

        strsql = "insert into prueba_arrays (tipo_intervencion) values "
        salida = "(array[" & resultado & "]);"




        DoCmd.SetWarnings False
        DoCmd.RunSQL strsql & salida
        DoCmd.SetWarnings True
End Sub

If I execute the result in PostgreSQL like "Insert into sometable (array_field) values (array['value1','value2','value3']);" 如果我在PostgreSQL中执行结果,例如“插入某个表(array_field)值(array ['value1','value2','value3']);“ it works fine. 它工作正常。 But in MS-Access it says: Error 3075 'execution time' Missing operator in the query 'array['value1','value2','value3']'. 但是在MS-Access中它说:错误3075'执行时间'查询'array ['value1','value2','value3']'中缺少运算符。 Any idea of what's happening? 有什么想法吗? Thanks in advance! 提前致谢!

The line DoCmd.RunSQL strsql & salida executes the SQL it the Access currentDb. DoCmd.RunSQL strsql & salida行在Access currentDb中执行SQL。 Replace that line with this: 将该行替换为:

db.Execute strsql & salida

So that the SQL gets executed from the Database object you have opened, and connected to PostgreSQL. 这样就可以从您打开的数据库对象执行 SQL,并连接到PostgreSQL。

DoCmd.RunSQL runs the SQL string through the Access Database Engine. DoCmd.RunSQL通过Access数据库引擎运行SQL字符串。 There [..] is interpreted as parameter, therefore the error message. 那里[..]被解释为参数,因此错误消息。

You have opened a db connection to the PostgreSQL database, but you don't use it. 您已打开与PostgreSQL数据库的数据库连接,但未使用它。

It might be as simple as changing 它可能像更改一样简单

DoCmd.RunSQL strsql & salida

to

db.Execute strsql & salida, dbSQLPassThrough

With a Pass-Through query the SQL string is passed directly to the database. 通过直通查询,SQL字符串直接传递到数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM