【问题标题】:Establish a connection to SQL Server with Visual Studio 2015 Windows Form App使用 Visual Studio 2015 Windows Form App 建立与 SQL Server 的连接
【发布时间】:2020-02-24 04:56:51
【问题描述】:

我正在尝试创建一个连接到 SQL Server 数据库的窗口窗体应用程序。我能够使用 Alteryx、Tableau、Python 和 Visual Studio 中的连接向导连接到数据库。但是,当我尝试在应用程序中创建连接时,它无法连接。我尝试过多种方式来做到这一点

  1. VB
  2. 使用 SqlClient 的 C#
  3. C# 使用配置文件(带有测试连接的详细信息)
  4. C# 使用 ODBC 驱动程序
/*************** ODBC Driver ***************/

using System;
using System.Windows.Forms;
using System.Data.Odbc;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            string connetionString = null;
            OdbcConnection cnn;

            connetionString = "Driver={SQL Server Native Client 11.0};
            Server=********;Database=********;Uid=********;Pwd=********;"; 

            cnn = new OdbcConnection(connetionString);

            try
            {

                cnn.Open();
                MessageBox.Show("Connection Open ! ");
                cnn.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("Can not open connection ! ");
            }

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

但是,当我运行此代码时,我收到以下错误

Activated Event Time Duration 线程异常:抛出异常: System.Data.dll 中的“System.Data.Odbc.OdbcException”(“错误 [08001] [Microsoft][SQL Server Native Client 11.0]TCP 提供者:A 数据库查找期间发生不可恢复的错误。

ERROR [HYT00] [Microsoft][SQL Server Native Client 11.0]登录超时 已过期错误 [08001] [Microsoft][SQL Server Native Client 11.0]A 发生网络相关或特定于实例的错误,同时 建立与 SQL Server 的连接。未找到服务器 无障碍。检查实例名称是否正确以及 SQL Server 是否正确 配置为允许远程连接。有关详细信息,请参阅 SQL 服务器联机丛书。”)。抛出异常: System.Data.dll 中的“System.Data.Odbc.OdbcException”(“错误 [08001] [Microsoft][SQL Server Native Client 11.0]TCP 提供者:A 数据库查找期间发生不可恢复的错误。

ERROR [HYT00] [Microsoft][SQL Server Native Client 11.0]登录超时 已过期错误 [08001] [Microsoft][SQL Server Native Client 11.0]A 发生网络相关或特定于实例的错误,同时 建立与 SQL Server 的连接。未找到服务器 无障碍。检查实例名称是否正确以及 SQL Server 是否正确 配置为允许远程连接。有关详细信息,请参阅 SQL 服务器在线图书。”)16.78s [22724]

作为比较,当我在 Python 中运行类似的脚本时,我可以毫无问题地连接到数据

/******** Python using Jupiter Notebook ********/

import pyodbc 
conn = pyodbc.connect('Driver={SQL Server Native Client 11.0};'
                      'Server=********;'
                      'Database=********;'
                      'Uid=********;'
                      'Pwd=********;')

cursor = conn.cursor()
cursor.execute('SELECT * FROM [********].[dbo].[********]')

for row in cursor:
    print(row)

如果我可以连接所有其他方式,为什么我不能通过 Windows 窗体应用程序进行连接。我假设我所有的 TCP/IP 设置都应该没问题?另外,我已经通过 Visual Studio 建立了连接。

【问题讨论】:

  • 嗯,我已经浏览了许多类似的帖子,并且已经检查过我使用的是默认实例,并且可以接受除外部连接之外的情况。我无法检查 TCP / IP 设置,因为我没有正确的权限,但由于我设法连接 Python,我假设这些都可以
  • 框架中还有一个类可能会有所帮助docs.microsoft.com/en-us/dotnet/api/…
  • @Mary - 谢谢,我已经使用了这两种资源,但无法破解它。我还关注了一个 youtube 视频,该视频为连接创建了一个单独的类,但这也不起作用。除非有人能看到我遗漏的上述代码有问题,否则我想知道是否是 Windows 窗体(与 Visual Studio 应用程序)特有的东西,包括特定的防火墙/其他权限。我真的迷失了这个!!

标签: c# sql-server vb.net database-connection


【解决方案1】:

我将ODBCConnection 更改为SQLConnection。这对我有用,但我绝不是专家。我在 VB.NET 中工作得更好,所以这段代码使用Telerik Code Converter 转换为 C#。我还在底部发布了 VB.NET 代码,以防转换中出现问题。

C# 代码

using System;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            TestConnection();
        }

        private void TestConnection()
        {
            string connectionString = null;
            SqlConnection cnn;
            SqlConnectionStringBuilder cnBuild = new SqlConnectionStringBuilder();
            cnBuild.DataSource = "Server";
            cnBuild.InitialCatalog = "databaseName";
            cnBuild.UserID = "userid";
            cnBuild.Password = "password";
            // connectionString = "Driver={SQL Server Native Client 11.0};Server=********;Database=********;Uid=********;Pwd=********;"
            cnn = new SqlConnection(cnBuild.ConnectionString);

            try
            {
                cnn.Open();
                MessageBox.Show("Connection Open ! ");
                cnn.Close();
            }
            catch (Exception __unusedException1__)
            {
                MessageBox.Show("Can not open connection ! ");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }
    }
}

VB.Net 代码


Imports System
Imports System.Windows.Forms
Imports System.Data.SqlClient

Namespace WindowsFormsApplication2
    Partial Public Class Form1
        Inherits Form

        Public Sub New()


            TestConnection()
        End Sub

        Private Sub TestConnection()

            Dim connectionString As String = Nothing
            Dim cnn As SqlConnection
            Dim cnBuild As New SqlConnectionStringBuilder
            cnBuild.DataSource = "Server"
            cnBuild.InitialCatalog = "databaseName"
            cnBuild.UserID = "userid"
            cnBuild.Password = "password"
            cnn = New SqlConnection(cnBuild.ConnectionString)

            Try
                cnn.Open()
                MessageBox.Show("Connection Open ! ")
                cnn.Close()
            Catch __unusedException1__ As Exception
                MessageBox.Show("Can not open connection ! ")
            End Try
        End Sub

        Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
        End Sub

        Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
        End Sub
    End Class
End Namespace

【讨论】:

  • 明天我会试试这个,一旦我回到办公室 - 谢谢
  • 嗨@DjJazzyJeffTN - C 代码有一些错误,所以我尝试了 VB。不确定它是否连接。 15 秒后它没有超时,但确实发送了一条消息说它已连接。我需要弄乱代码以使其在单击按钮时打开连接以进行检查,但没有机会 atm
  • 我担心 C# 转换器会出现这种情况。我很高兴 VB 代码为您工作。既然您说它有效,那么您介意将其标记为答案吗?由于问题似乎是不正确的连接字符串。谢谢,编码愉快。
  • 我需要测试它是否真的建立了连接。抱歉,现在忙于其他事情。当我有空闲时间时,我会回到这个并标记正确。谢谢
  • 想知道您是否测试过我与您分享的代码?
猜你喜欢
  • 2023-03-28
  • 2014-05-09
  • 1970-01-01
  • 2018-06-03
  • 2017-11-22
  • 1970-01-01
  • 2013-09-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多