【问题标题】:Create a SQLite database using ADODB.Connection使用 ADODB.Connection 创建 SQLite 数据库
【发布时间】:2018-09-09 09:01:29
【问题描述】:

我有一个可能很容易解决的问题,但我在文档或任何网站(例如 StackOverflow)中都找不到任何内容。

我正在将信息从 CSV 导入 SQLite3 数据库,为此我使用以下例程来支持我的导入例程

  Sub runSQLiteQuery(path As String, strSQL As String)    

    Dim conn As Object, rst As Object

    Set conn = CreateObject("ADODB.Connection")
    Set rst = CreateObject("ADODB.Recordset")

    ' OPEN CONNECTION
    conn.Open "DRIVER=SQLite3 ODBC Driver;Database=" & path & ";"

    ' OPEN RECORDSET
    rst.Open strSQL, conn
    rst.Close
    ' FREE RESOURCES
    Set rst = Nothing: Set conn = Nothing

End Sub

我的问题是:

首先如何创建数据库文件?

我在 cmd 中使用从 SQLite3 命令创建的文件并从中导入 csv,但这对于我的 Excel 需求来说不是一个好的解决方案。

提前致谢!

【问题讨论】:

    标签: database vba sqlite adodb


    【解决方案1】:

    我刚刚找到了方法。

    最简单的方法是使用以下代码:

    Sub runSQLiteQuery(path As String, strSQL As String)    
    
        Dim conn As Object, rst As Object
    
        Set conn = CreateObject("ADODB.Connection")
        Set rst = CreateObject("ADODB.Recordset")
    
        ' OPEN CONNECTION
        conn.Open "DRIVER=SQLite3 ODBC Driver;Database=" & path & ";"
    
        ' OPEN RECORDSET
        rst.Open strSQL, conn
        rst.Close
        ' FREE RESOURCES
        Set rst = Nothing: Set conn = Nothing
    
    End Sub
    

    然后,创建我们只需要使用的数据库文件:

    Sub startDb()
        Dim dbPath As String
        dbPath = Application.ActiveWorkbook.path
    
        ' Checks if Db exists. If not, creates
        If Dir(dbPath & "Db.s3db", vbDirectory) = "" Then Call runSQLiteQuery(dbPath & "\Db.s3db", "SELECT 1;")
    End Sub
    

    【讨论】:

    【解决方案2】:
    'use excel 2016 vba    
    Dim conn As Object
    Set conn = CreateObject("ADODB.Connection")
    newdb = "F:\sqlite3win64\test.db3"
    conn.Open "DRIVER=SQLite3 ODBC Driver;Database=" & newdb  
    

    【讨论】:

    • 欢迎来到 StackOverflow!虽然此答案可能会解决 OP 的问题,但建议提供有关书面代码的解释,以使您的答案更容易被社区理解并提高其质量
    猜你喜欢
    • 2018-09-15
    • 2011-10-07
    • 2014-12-29
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多