vba Excel连接数据库postgres

第一步 在网上下载postres的驱动程序,之后安装,下载地址:https://www.devart.com/odbc/postgresql/download.html

第二步 创建ODBC数据源

点击“开始-》控制面板-》管理工具-》数据源(ODBC)-》用户DSN-》添加”

安装上图配置好之后写入VBA代码

Private Sub CommandButton1_Click()

    Dim cnn As New ADODB.Connection
    Dim rs As New ADODB.Recordset
    Dim dataBase As String
    Dim userName As String
    Dim password As String
    Dim DBname As String
    Dim openCommand As String
    dataBase = "PostgreSQL35W"
    userName = "postgres"
    password = "test1234"
    DBname = "testRPA"
    openCommand = "DSN=" & dataBase & ";" & "UID=" & userName & ";" & "PWD=" & password & ";" & "Database=" & DBname
    cnn.Open openCommand
    Dim SQL As String
    '検索
    SQL = "select id from test where ID = '1001'"
    rs.Open SQL, cnn
    While Not rs.EOF
        MsgBox rs!ID
        rs.MoveNext
    Wend
    rs.Close
    cnn.Close
    Set rs = Nothing
    Set cn = Nothing
    
    '削除
    SQL = "delete from test where ID = '1001'"
    Call cnn.Execute(SQL)
    
    '修正
    SQL = "update test set NAME = 'name123' where ID = '1002'"
    Call cnn.Execute(SQL)
    
    
    
End Sub

执行即可!

猜你喜欢

转载自www.cnblogs.com/killclock048/p/9402390.html