连接到SQL Server 2012与C#数据库(Visual Studio中2012) [英] Connect to SQL Server 2012 Database with C# (Visual Studio 2012)

查看:707
本文介绍了连接到SQL Server 2012与C#数据库(Visual Studio中2012)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

晚上所有,

我试图连接到从C#中的SQL Server 2012数据库。使用SQL Server Management Studio时我的连接设置如下: -

I'm trying to connect to a SQL Server 2012 database from C#. My connection settings when using SQL Server Management Studio are as below:-

Server Type:    Database Engine
Server Name:    Paul-PC\SQLEXPRESS
Authentication: Windows Authentication
Username:   Greyed out
Password:   Greyed out 

我试图连接数据库的名称是TESTDB

The name of the database I'm trying to connect to is "testDB".

下面是我的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

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

        private void btnConnect_Click(object sender, EventArgs e)
        {
            SqlConnection myConnection = new SqlConnection("server=localhost;" +
                                       "Trusted_Connection=yes;" +
                                       "database=testDB; " +
                                       "connection timeout=30");
            try
            {
                myConnection.Open();
                MessageBox.Show("Well done!");
            }
            catch(SqlException ex)
            {
               MessageBox.Show("You failed!" + ex.Message);
            }

        }
    }
}

不幸的是,我的代码无法与以下错误连接: -

Unfortunately, my code fails to connect with the following error:-

你没在建立连接时出现与网络相关的或特定于实例的错误! SQL服务器,服务器找不到或无法访问。验证实例名称是否正确,以及SQL Server配置为允许远程连接。

"You failed!A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections."

有什么建议? SQL服务器是在本地运行。

Any suggestions? SQL Server is running locally.

推荐答案

在您的连接字符串替换服务器=本地主机服务器=保罗 - PC\\SQLEXPRESS;

In your connection string replace server=localhost with "server = Paul-PC\\SQLEXPRESS;"

这篇关于连接到SQL Server 2012与C#数据库(Visual Studio中2012)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆