2016-06-15 61 views
-1

我有問題,當我嘗試選擇加入與附加數據庫命令從不同的SQLite數據庫表和把值到datagridview的附加2 SQLite數據庫,然後選擇表

他們得到許多錯誤如:數據庫無法打開,ExuteNonQuery錯誤,無法打開連接,無法打開數據庫。

pathinfo2作爲我的主數據庫和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 

有任何人知道如何解決它?

+0

如果回答了這個問題,請點擊對號,以便將此帖子移出未回覆列表。 – Plutonix

回答

1

這正常打開,連接和查詢二次DB:

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 

一個你想要做的是正確地引用數據庫文件附加的東西(和主數據庫文件這件事),和一個文本框(即用戶輸入)是一個不好的開始。類似這樣的:

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

將文件名放入刻度中有助於防止文件名在路徑中包含空格時被錯誤地讀取。

如果/當您關閉(或丟棄)連接時,附件將丟失,因此您可能需要創建一個方法來打開並附加其他數據庫,並返回一個DBConnection對象。

+0

'path.combine(...)'msg =「路徑結合不是一串字符串」在嘗試附加db2時無法排除。錯誤消息=「C:\我的路徑數據庫無法打開數據庫」。 @Plutonix還有另一個解決方案嗎?之前感謝,我新使用vb; – jojodog

+0

'Path'是'System.IO'的成員。將'Imports System.IO'添加到文件的頂部。但是''不是字符串'的一部分'聽起來像你實現它不正確 – Plutonix