附加2个sqlite数据库并选择表

时间:2016-06-15 16:52:49

标签: vb.net sqlite

当我尝试使用attach database命令从不同的sqlite数据库中选择连接表并将值放入datagridview时,我遇到了问题

他们得到很多错误,例如:数据库无法打开,ExuteNonQuery错误,无法打开连接,无法打开数据库。

pathinfo2作为我的主db,pathinfo1作为我的db2

这是我的代码:

Sub slc_smscontact()
    Dim fc1 As String = "Data Source=" + pathinfo2.Text + ";Version=3;"
    Dim SQL As String = "ATTACH '" + pathinfo1.Text + "' AS db2"
    Dim com As New SQLiteCommand(SQL)
    Dim connection As SQLiteConnection = New SQLiteConnection(fc1)
    'connection.ConnectionString = fc1
    com.Connection = connection
    connection.Open()
    Dim retval As Integer = 0
    Try
        retval = com.ExecuteNonQuery()
    Catch ex As Exception
        MessageBox.Show("An error occurred, your attach databases was not completed.")
    Finally
        com.Dispose()
    End Try

    SQL = "select distinct a.data1 no_telp, b.data1 nama, db2.sms.address, db2.sms.body, db2.sms.date, db2.sms.date_sent, db2.sms.Thread_id from (select raw_contact_id,data1 from data where mimetype_id = 5) as a, (select raw_contact_id,data1 from data where mimetype_id = 7) as b where a.raw_contact_id = b.raw_contact_id INNER JOIN db2.sms ON data.no_telp = db2.sms.address;"
    com = New SQLiteCommand(SQL)
    com.Connection = connection
    'retval = 0
    Try
        Dim ds3 As New DataSet()
        Dim da3 As New SQLiteDataAdapter(com)
        da3.Fill(ds3)
        grid3.DataSource = ds3.Tables(0).DefaultView
        'retval = com.ExecuteNonQuery()
    Catch ex As Exception
        MessageBox.Show("An error occurred, your select was not completed.")
    Finally
        'com.Dispose()
        connection.Close()
    End Try
End Sub

有谁知道如何修复它?

1 个答案:

答案 0 :(得分:1)

这适用于打开,附加和查询辅助数据库:

Dim SQL = "SELECT Id, Name, Fish, Bird FROM db2.Example"
' "attachment" string
Dim sqlAtt = String.Format("ATTACH '{0}' AS {1} ", sqlFile, "db2")

' connect to "main" db
Using dbcon As New SQLiteConnection(LiteConnStr)

    ' create a command just for the attaching
    Using cmdAtt As New SQLiteCommand(sqlAtt, dbcon)

        dbcon.Open()
        ' execute attachment
        cmdAtt.ExecuteNonQuery()

        ' now run a query on db2 from connection to db1
        Using cmd As New SQLiteCommand(SQL, dbcon)

            dtSample = New DataTable
            dtSample.Load(cmd.ExecuteReader)
            dgv2.DataSource = dtSample
        End Using
    End Using
End Using

您要做的一件事就是正确引用要附加的db文件(以及相关的主db文件),而TextBox(即用户输入)是一个糟糕的开始。像这样:

sqlFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                                         "SQLite dbs", "secondary.db")
Dim sqlAtt = String.Format("ATTACH '{0}' AS {1} ", sqlFile, "db2")

将文件名包含在刻度中有助于防止在路径包含空格时错误地读取它。

如果/当您关闭(或处置)连接时,附件将丢失,因此您可能希望创建一个方法来打开并附加其他数据库并返回DBConnection对象。