如何摆脱此错误:ConnectionString中未指定OLE DB提供程序。一个例子是,' Provider = SQLOLEDB;'

时间:2015-06-19 14:39:41

标签: sql-server vb.net

我的应用程序的目的是当用户键入客户,他们的用户名和消息到相应的文本框中时,它应该在用户按下发送按钮后记录在SQL Server上的表中。

这是我的代码:

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

我收到以下错误:

  

ConnectionString中未指定OLE DB提供程序。一个例子是,'提供商= SQLOLEDB;'。

我做错了什么,以及如何解决这个问题。

3 个答案:

答案 0 :(得分:4)

看起来您正在尝试将SQL Server连接字符串提供给OleDbConnection。您需要使用SqlConnection打开该连接字符串,否则您需要创建一个有效的OLEDB连接字符串以指向该数据库。有关参考,请参阅this site

答案 1 :(得分:2)

如果要连接到MS SQL数据库,则应使用SQL connection而不是OleDbConnection。

对于OldDbommand,sqlCommand也是如此。

这个SO question作为解释Sql和OldDb Client之间差异的答案。

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

答案 2 :(得分:1)

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