简体   繁体   English

如何使用VB连接到SQL Server?

[英]How do I connect to SQL Server with VB?

I'm trying to connect to a SQL server from VB. 我正在尝试从VB连接到SQL服务器。 The SQL server is across the network uses my windows login for authentication. 跨越网络的SQL服务器使用我的Windows登录进行身份验证。

I can access the server using the following python code: 我可以使用以下python代码访问服务器:

import odbc
conn = odbc.odbc('SignInspection')
c = conn.cursor()
c.execute("SELECT * FROM list_domain")
c.fetchone()

This code works fine, returning the first result of the SELECT. 这段代码工作正常,返回SELECT的第一个结果。 However, I've been trying to use the SqlClient.SqlConnection in VB, and it fails to connect. 但是,我一直在尝试在VB中使用SqlClient.SqlConnection,它无法连接。 I've tried several different connection strings but this is the current code: 我尝试了几种不同的连接字符串,但这是当前的代码:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim conn As New SqlClient.SqlConnection
    conn.ConnectionString = "data source=signinspection;initial catalog=signinspection;integrated security=SSPI"
    Try
        conn.Open()
        MessageBox.Show("Sweet Success")
        ''#Insert some code here, woo
    Catch ex As Exception
        MessageBox.Show("Failed to connect to data source.")
        MessageBox.Show(ex.ToString())
    Finally
        conn.Close()
    End Try

End Sub

It fails miserably, and it gives me an error that says "A network-related or instance-specific error occurred... (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) 它失败了,它给了我一个错误,上面写着“发生与网络相关或特定于实例的错误......”(提供者:命名管道提供程序,错误:40 - 无法打开与SQL Server的连接)

I'm fairly certain it's my connection string, but nothing I've found has given me any solid examples (server=mySQLServer is not a solid example) of what I need to use. 我很确定这是我的连接字符串,但我发现的任何东西都没有给我任何可靠的例子(server = mySQLServer不是一个可靠的例子)。

Thanks! 谢谢! -Wayne -Wayne

Check out connectionstrings.com for samples. 查看connectionstrings.com的样品。 It looks like in your python example, you are accessing the DB via ODBC. 看起来在你的python示例中,你是通过ODBC访问数据库。

The string you are using is connecting with the built in .NET SQL Server DB provider, so you need to use an ODBC connection string OR change your data source to the actual server name (if no other instances) or servername/instance name. 您使用的字符串是与内置的.NET SQL Server数据库提供程序连接,因此您需要使用ODBC连接字符串或将数据源更改为实际的服务器名称(如果没有其他实例)或servername / instance name。

You are using an ODBC DSN as a SqlClient server name. 您正在使用ODBC DSN作为SqlClient服务器名称。 This is not going to work. 这不会起作用。 You have to use a SqlClient connection string, and for SqlClient the DataSource property is the server name or a SQL Native Client server alias (which is not the same as an ODBC DSN). 您必须使用SqlClient连接字符串,对于SqlClient,DataSource属性是服务器名称或SQL Native Client服务器别名(与ODBC DSN不同)。

Replace signinspection with the actual name of your SQL Server host. signinspection替换为SQL Server主机的实际名称。 If is a named instance or listening on a non default port, you have to specify that too, eg: hostname\\instancename 如果是命名实例或侦听非默认端口,则还必须指定,例如: hostname\\instancename

Sure your Server and Database have the same name? 确定您的服务器和数据库具有相同的名称?

Here you have a link that would allow you to generate a connection string and test it 这里有一个链接,允许您生成连接字符串并对其进行测试

http://blogs.msdn.com/dhejo_vanissery/archive/2007/09/07/One-minute-Connection-string.aspx . http://blogs.msdn.com/dhejo_vanissery/archive/2007/09/07/One-minute-Connection-string.aspx

Well, I went ahead and used an ODBC Connection. 好吧,我继续使用ODBC连接。 It appears that that is what I was wanting in the first place. 看起来这就是我首先想要的东西。

In order to do use the ODBC I had to go to http://support.microsoft.com/kb/310985 and install a few files. 为了使用ODBC,我必须访问http://support.microsoft.com/kb/310985并安装一些文件。 Following the directions I came up with the following code that seems to work just fine: 按照指示,我想出了以下代码似乎工作得很好:

Dim conn As OdbcConnection
conn = New OdbcConnection("DSN=SignInspection")
Dim mystring as String = "SELECT * FROM list_domain"
Dim cmd As OdbcCommand = New OdbcCommand(mystring, conn)
Dim reader As OdbcDataReader
Dim columnCount As Integer
Dim output As String
Dim data as Object() = New Object(10) {}
conn.Open()
MsgBox("Connected!")
reader = cmd.ExecuteReader()
While reader.Read()
    columnCount = reader.GetValues(data)
    output = ""
    For i As Integer = 0 To columnCount - 1
        output = output & " " & data(i).ToString()
    Next
    Debug.WriteLine(output)
End While
conn.Close()

Of course I'll have it cleaned up a lot, but I figure maybe someone will end up looking for the same solution, and maybe they'll see my code before they spend too much time. 当然我会清理它很多,但我想也许有人会最终寻找相同的解决方案,也许他们会在花费太多时间之前看到我的代码。

ed. 编辑。 columsCount -> columCount columsCount - > columCount

You might want to take a look on Microsoft Enterprise Library Data Access Application Block in order to make it easier to connect and to support multiple underlying datastores. 您可能需要查看Microsoft Enterprise Library Data Access Application Block ,以便更轻松地连接和支持多个基础数据存储。

Good success! 好成功! =) =)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM