code

SQL Server 연결 문자열을 설정하는 방법은 무엇입니까?

codestyles 2020. 10. 16. 07:26
반응형

SQL Server 연결 문자열을 설정하는 방법은 무엇입니까?


간단한 C # 응용 프로그램을 개발 중입니다.이 내용을 알고 싶습니다. 응용 프로그램을 PC의 SQL Server에 연결할 때 연결 문자열 (서버 이름, 암호 등)을 알고 있지만 다른 응용 프로그램에 연결할 때 PC에서 SQL Server 연결 문자열이 다릅니다. 연결할 수있는 기본 계정과 함께 제공되는 SQL Server에 공통 계정이 있습니까? saSQL Server의 계정에 대해 들었습니다 . 무엇 sa입니까?


// .NET DataProvider-사용자 이름과 암호를 사용한 표준 연결

using System.Data.SqlClient;

SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"User id=UserName;" +
"Password=Secret;";
conn.Open();

// .NET DataProvider-신뢰할 수있는 연결

SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"Integrated Security=SSPI;";
conn.Open();

실제로 SqlConnectionStringBuilder클래스를 사용하여 연결 문자열 을 작성할 수 있습니다 . 연결 문자열 을 작성하려면 해당 개체를 인스턴스화 SqlConnectionStringBuilder하고 데이터베이스에 연결하는 데 사용하는 매개 변수로 해당 속성을 설정해야합니다. 그런 다음 이 예제에 표시된대로 개체 속성에서 연결 문자열가져올 수 있습니다 .ConnectionStringSqlConnectionStringBuilder

예를 들면 :

    SqlConnectionStringBuilder sConnB = new SqlConnectionStringBuilder ()
    {
        DataSource = "ServerName",
        InitialCatalog = "DatabaseName",
        UserID = "UserName",
        Password = "UserPassword"
    }.ConnectionString

SqlConnection conn = new SqlConnection(sConnB.ConnectionString);

new연산자를 사용하여 직접 만들 수 있습니다.

예를 들면 :

SqlConnection conn = new SqlConnection(
    new SqlConnectionStringBuilder ()
    {
        DataSource = "ServerName",
        InitialCatalog = "DatabaseName",
        UserID = "UserName",
        Password = "UserPassword"
    }.ConnectionString
);

더 많은 매개 변수를 추가하여 연결 문자열 을 만들 수 있습니다 . 매개 변수는 SqlConnectionStringBuilder개체 속성 에 설정된 값으로 정의됩니다 .

또한 연결된 DB와 Microsoft Visual Studio의 연결에서 데이터베이스 연결 문자열을 가져올 수 있습니다. DB를 선택하면 속성 패널에 연결 문자열 이 표시 됩니다.

SqlConnectionStringBuilder클래스 의 전체 속성 목록은 Microsoft MSDN 사이트 의이 페이지에 나열되어 있습니다.

SQL Server의 기본 사용자에 대해 sa 는 "시스템 관리자"를 의미하며 해당 암호는 SQL Server 버전에 따라 다릅니다. 페이지 에서 암호가 어떻게 다른지 확인할 수 있습니다.

SQL Server 2008 / R2 Express 사용자 : sa 암호 : [빈 암호-연결하려면 필드를 비워 두십시오.]

SQL Server 201x Express 사용자 : sa 암호 : Password123

SQL Server 20xx 웹 또는 표준 사용자 : sa 암호 : VDS가 프로비저닝 될 당시의 관리자 또는 루트 사용자 암호와 동일합니다.

SQL Server 데이터베이스 관리자를 시작할 때이 로그인 창에서 sa 사용자로 로그인 할 수 있습니다 . 이 이미지에서와 같이 :

Log in example


.NET 데이터 공급자-기본 상대 경로-표준 연결

 using System.Data.SqlClient;
 var conn = new SqlConnection();
 conn.ConnectionString = 
 "Data Source=.\SQLExpress;" + 
 "User Instance=true;" + 
 "User Id=UserName;" + 
 "Password=Secret;" + 
 "AttachDbFilename=|DataDirectory|DataBaseName.mdf;"conn.Open();

.NET 데이터 공급자-기본 상대 경로-신뢰할 수있는 연결

 using System.Data.SqlClient;
 var conn = new SqlConnection();
 conn.ConnectionString = 
 "Data Source=.\SQLExpress;" + 
 "User Instance=true;" + 
 "Integrated Security=true;" + 
 "AttachDbFilename=|DataDirectory|DataBaseName.mdf;" conn.Open();

.NET 데이터 공급자-사용자 지정 상대 경로-표준 연결

using System.Data.SqlClient;
AppDomain.CurrentDomain.SetData(
"DataDirectory", "C:\MyPath\");
 var conn = new SqlConnection();
 conn.ConnectionString = 
 "Data Source=.\SQLExpress;" + 
 "User Instance=true;" + 
 "User Id=UserName;" + 
 "Password=Secret;" + 
"AttachDbFilename=|DataDirectory|DataBaseName.mdf;" conn.Open();  

.NET 데이터 공급자-사용자 지정 상대 경로-신뢰할 수있는 연결

 using System.Data.SqlClient;
 AppDomain.CurrentDomain.SetData(
 "DataDirectory", "C:\MyPath\");
 var conn = new SqlConnection();
 conn.ConnectionString = 
 "Data Source=.\SQLExpress;" + 
 "User Instance=true;" + 
 "Integrated Security=true;" + 
 "AttachDbFilename=|DataDirectory|DataBaseName.mdf;" conn.Open();

다른 컴퓨터의 SQL Server에 연결할 때 걱정해야 할 사항이 많습니다.

  • 기기의 호스트 / IP 주소
  • 초기 카탈로그 (데이터베이스 이름)
  • 유효한 사용자 이름 / 암호

Very often SQL server may be running as a default intance which means you can simply specify the hostname/ip address but you may encounter a scenario where it is running as a named instance (Sql Express for instance). In this scenario you'll have to specify hostname\instance name .


You can use the connection string as follows and you only need to add your database name.

string connetionString = "Data Source=.;Initial Catalog=DB name;Integrated Security=True;MultipleActiveResultSets=True";

You need to understand that a database server or DBA would not want just anyone to be able to connect or modify the contents of the server. This is the whole purpose of security accounts. If a single username/pwd would work on just any machine, it would provide no protection. That "sa" thing you have heard of, does not work with SQL Server 2005, 2008 or 2012. Not sure about previous versions though. I believe somewhere in the early days of SQL Server, the default username and pwd used to be sa/sa, but that is no longer the case.

FYI, database security and roles are much more complicated now-a-days. You may want to look into the details of Windows-based authentication. If your SQL Server is configured for it, you don't need any username/pwd in the connection string to connect to it. All you need to change is the server machine name and the same connection string will work with both your machines, given both have same db name of course.


You can use either Windows authentification, if your server is in Domain, or Sql authentification. Sa - is a System Administratior, the root account for SQL server authentification. But it is a bad practice to use if for conneting of your clients. You should create your own accounts, and use them to connect to your SQL. In each connection you set account login, its password and the default database, you want to connect.


sa is a system administrator account which comes with sql server by default. As you know might already know, you can use two ways to log in to SQL Server.

screen shot of SQL Server Management Studio

Therefore there are connection strings which suitable for each scenario(such as windows authentication, localdb etc.). Use https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx#sqlserver to build your connection string. These are XML tags. You just need value of connectionString


We can simply connect to database:

 uid=username;pwd=password;database=databasename;server=servername

E.g.:

string connectionString = @"uid=spacecraftU1;pwd=Appolo11;
                            database=spacecraft_db;
                            server=DESKTOP-99K0FRS\\PRANEETHDB";
SqlConnection con = new SqlConnection(connectionString);

"ConnectionString":{
  "Database_Name": "server=.;database=Database_Name;Integrated Security=true;"
},

Try this one

참고URL : https://stackoverflow.com/questions/15631602/how-to-set-sql-server-connection-string

반응형