2015-06-19 36 views
-1

我的應用程序的目的是,當用戶輸入一個客戶,他們的用戶名和消息到各自的文本框中時,應該在用戶按下發送按鈕後將其記錄到SQL Server上的表中。如何擺脫此錯誤:未在ConnectionString中指定OLE DB提供程序。一個例子是'Provider = SQLOLEDB'

這裏是我的代碼:

Public Class Form1 

Dim Con As OleDbConnection 
Dim cmd As New OleDbCommand 

Dim conString As String = "Data Source=176.111.555.24;Initial Catalog=MyDatabase;User ID=Username;Password=Password" 

Public Sub MessageSent() 

    Try 

     Dim con As New OleDbConnection 
     con.ConnectionString = conString 
     con.Open() 

     cmd.Connection = con 

     cmd.CommandText = "insert into tblmessage(Customer, UserName, Message) values('" & txtCustomer.Text & "', '" & txtUserName.Text & "', '" & rtfMessage.Text & "')" 


     cmd.ExecuteNonQuery() 

     con.Close() 
     MsgBox("Message Sent") 

     con.Close() 
     con.Dispose() 

    Catch ex As Exception 
     MsgBox(ex.Message) 

    End Try 

End Sub 

    Private Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click 
     MessageSent() 
    End Sub 

,我發現了以下錯誤:

An OLE DB Provider was not specified in the ConnectionString. An example would be, 'Provider=SQLOLEDB;'.

它是什麼,我做錯了,這可怎麼解決。

+0

如果數據庫是SQL Server爲什麼你使用OleDB? – Plutonix

+0

你會如何重寫? – Dave

+0

好的。抱歉!我下次會做得更好! – Dave

回答

1
Dim conString As String = "Provider=SQLOLEDB;Data Source=176.111.555.24;Initial Catalog=MyDatabase;User ID=Username;Password=Password" 
+0

這工作!謝謝! – Dave

4

它看起來像你試圖給一個SQL Server連接字符串到OleDbConnection。您需要使用SqlConnection以使用該連接字符串打開,否則您需要創建一個有效的OLEDB連接字符串以指向該數據庫。有關參考,請參見this site

+0

問題:如何使這段代碼不被硬編碼: – Dave

+0

Dim conString As String =「Data Source = 176.111.555.24; Initial Catalog = MyDatabase; User ID = Username; Password = Password」 – Dave

+0

我想用這樣的東西: Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings(「conStr」)。ConnectionString) – Dave

2

當您想連接到MS SQL數據庫時,應該使用SQL connection而不是OleDbConnection。

sqlCommand與OldDbommand相同。

這個SO question作爲解釋Sql和OldDb客戶端之間差異的一些答案。

Public Sub MessageSent() 

    Try 
    Using con As SqlConnection = New SqlConnection 


     con.ConnectionString = "Data Source=176.111.555.24;Initial Catalog=MyDatabase;User ID=Username;Password=Password" 
     con.Open() 

     Using cmd As New SqlCommand 
     cmd.Connection = con 
     cmd.CommandText = "insert into tblmessage(Customer, UserName, Message) values('" & txtCustomer.Text & "', '" & txtUserName.Text & "', '" & rtfMessage.Text & "')" 
     cmd.ExecuteNonQuery() 
     End Using 

     MsgBox("Message Sent") 
     con.Close()   


    End Using 


    Catch ex As Exception 
    MsgBox(ex.Message) 
    End Try 

End Sub 
+0

而不是全局聲明: Dim Con As SqlConnection Dim cmd As New SqlCommand 我可以把它們放到我的子程序中嗎? – Dave

+1

我沒有改變它的例子,但是,你應該總是儘量避免使用全局實例,如果你不需要。 –

+1

將[sql語句](https://msdn.microsoft.com/zh-cn/library/htd05whh.aspx)中的sqlConnection/sqlCommand包裝起來以使它們正確放置也是一種很好的做法。 –

相關問題