使用C#中的默认连接字符串连接到SQL Server数据库

时间:2022-04-11 10:16:38

I've been trying to make a connection with my SQL Server database (Mynewdatabase) using the default connection string that was generated (supposedly) when I added the data source for this project. However, I'm thus far unable to make a connection: I'm getting an error that "the server was not found or was not accessible".

我一直在尝试使用我为此项目添加数据源时生成的(默认)生成的默认连接字符串与我的SQL Server数据库(Mynewdatabase)建立连接。但是,我到目前为止无法建立连接:我收到的错误是“服务器未找到或无法访问”。

This my code. Thanks so much for any help you can offer:

这是我的代码。非常感谢您提供的任何帮助:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;

namespace Parsevcf2sql
{
class Program
{
    static void Main(string[] args)
    {
        // here is where I get what I believe is an appropriate connection string
        string cs = Parsevcf2sql.Properties.Settings.Default.MynewdatabaseConnectionString;
        SqlConnection myconnection = new SqlConnection(cs);

        Console.WriteLine(cs);

        try
        {
            myconnection.Open();
            Console.WriteLine("This worked!");
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
  }
}

1 个解决方案

#1


0  

This might help you out, change localhost to your address and database name as well.. But Please check sql server must be in running mode

这可能会帮助你,将localhost更改为你的地址和数据库名称。但是请检查sql server必须处于运行模式

{
    // connection string!
    SqlConnection myConn = new SqlConnection("Server=localhost\\SQLEXPRESS;Integrated security=SSPI;database=Mynewdatabase;");

    try
    {
        myConn.Open();
        Console.WriteLine(myConn );
    }
    catch (System.Exception)
    {
       // some exception
    }
    finally
    {
        if (myConn.State == ConnectionState.Open)
        {
            myConn.Close();
        }
        myConn.Dispose();
    }
}

or check out this tutorial

或者查看本教程

#1


0  

This might help you out, change localhost to your address and database name as well.. But Please check sql server must be in running mode

这可能会帮助你,将localhost更改为你的地址和数据库名称。但是请检查sql server必须处于运行模式

{
    // connection string!
    SqlConnection myConn = new SqlConnection("Server=localhost\\SQLEXPRESS;Integrated security=SSPI;database=Mynewdatabase;");

    try
    {
        myConn.Open();
        Console.WriteLine(myConn );
    }
    catch (System.Exception)
    {
       // some exception
    }
    finally
    {
        if (myConn.State == ConnectionState.Open)
        {
            myConn.Close();
        }
        myConn.Dispose();
    }
}

or check out this tutorial

或者查看本教程