program story

ASP.NET에서 SQL SERVER에 대한 연결 문자열 설정

inputbox 2020. 8. 31. 07:45
반응형

ASP.NET에서 SQL SERVER에 대한 연결 문자열 설정


web.config 파일 (Visual Studio 2008 / ASP.NET 3.5)에서 로컬 서버 (SQL Server 2008)에 연결 문자열을 설정하려고합니다.

내 web.config에서 연결 문자열을 어디에 어떻게 배치합니까?

현재 web.config 파일은 다음과 같습니다. http://imwired.net/aspnet/Online_web.config


이것을 사용할 수도 있습니다. 더 간단합니다. 설정해야하는 유일한 것은 "YourDataBaseName"입니다.

  <connectionStrings>
    <add name="ConnStringDb1" connectionString="Data Source=localhost;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
  </connectionStrings>

연결 문자열 을 배치 할 위치

<?xml version='1.0' encoding='utf-8'?>  
  <configuration>  
    <connectionStrings>  
      <clear />  
      <add name="Name"   
       providerName="System.Data.ProviderName"   
       connectionString="Valid Connection String;" />  
    </connectionStrings>  
  </configuration>  

어떤 이유로 나는 여기서 간단한 답을 보지 못합니다.

이것을 코드 맨 위에 넣으십시오.

using System.Web.Configuration;
using System.Data.SqlClient; 

이것을 Web.Config에 넣으십시오.

<connectionStrings >
    <add
         name="myConnectionString" 
         connectionString="Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;"
         providerName="System.Data.SqlClient"/>
</connectionStrings>

연결 변수를 설정하려는 위치 :

SqlConnection con = new SqlConnection(
    WebConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);

나는 이것이 답을 얻기가 매우 어려웠다는 것을 알았지 만 결국 그것을 알아 냈습니다. 그래서 아래 단계를 작성하겠습니다.

  1. 코드에서 연결 문자열을 설정하기 전에 실제로 데이터베이스에 액세스 할 수 있는지 확인하십시오. SSMS (Sql Server Management Studio 또는 다른 데이터베이스와 동일)를 사용하여 데이터베이스 서버에 로컬로 로그인하여 사용하려는 세부 정보를 사용하여 액세스 할 수 있는지 확인하십시오.

  2. 다음으로 (필요한 경우) 별도의 서버에서 데이터베이스에 액세스하려는 경우 SSMS에서도 마찬가지로 수행 할 수 있는지 확인합니다. 따라서 컴퓨터에 SSMS를 설정하고 해당 데이터베이스 서버에 대한 사용자 이름과 암호를 사용하여 서버에 액세스 할 수 있는지 확인하십시오.

위의 2 가지 사항을 제대로 이해하지 못하면 데이터베이스에 액세스 할 수 없기 때문에 시간을 낭비하는 것입니다. 이는 설정 한 사용자가 잘못되었거나 원격 액세스가 활성화되지 않았거나 (필요한 경우) 포트가 열리지 않았기 (필요한 경우), 여러 다른 이유 중에서도 가장 일반적인 이유 일 수 있습니다.

SSMS를 사용하여 데이터베이스에 액세스 할 수 있는지 확인한 후. 프로세스를 자동화하고 실수를 방지하기위한 다음 단계는 시스템이 작업을 수행하도록하는 것입니다.

  1. 빈 프로젝트를 시작하고 Linq를 SQL 또는 Dataset에 추가하고 (EF는 좋지만 연결 문자열은 EF con 문자열 내부에 포함되어 있으므로 깨끗한 문자열을 원합니다) 위에서 확인한 세부 정보를 사용하여 데이터베이스에 연결합니다. 사기 문자열 위자드. 테이블을 추가하고 파일을 저장하십시오.

이제 웹 구성으로 이동하면 마술처럼 필요한 모든 세부 정보와 함께 깔끔하게 작동하는 연결 문자열이 표시됩니다.


{아래는 이전 게시물의 일부이므로 무시할 수 있습니다. 코드 뒤에있는 데이터베이스에 액세스하는 가장 기본적인 방법으로 참고 용으로 남겨 둡니다. 아래로 스크롤하여 아래 2 단계부터 계속하십시오. }

Lets assume the above steps start you off with something like the following as your connection string in the code behind:

string conString = "Data Source=localhost;Initial Catalog=YourDataBaseName;Integrated Security=True;";

This step is very important. Make sure you have the above format of connection string working before taking the following steps. Make sure you actually can access your data using some form of sql command text which displays some data from a table in labels or text boses or whatever, as this is the simplest way to do a connection string.

Once you are sure the above style works its now time to take the next steps:

1. Export your string literal (the stuff in the quotes, including the quotes) to the following section of the web.config file (for multiple connection strings, just do multiple lines:

<configuration>
    <connectionStrings>
        <add name="conString" connectionString="Data Source=localhost;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
        <add name="conString2" connectionString="Data Source=localhost;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
        <add name="conString3" connectionString="Data Source=localhost;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

{ The above was part of an old post, after doing the top 3 steps this whole process will be done for you, so you can ignore it. I just leave it here for my own reference. }


2. Now add the following line of code to the C# code behind, prefrably just under the class definition (i.e. not inside a method). This points to the root folder of your project. Essentially it is the project name. This is usually the location of the web.config file (in this case my project is called MyProject.

static Configuration rootWebConfig = WebConfigurationManager.OpenWebConfiguration("/MyProject");

3. Now add the following line of code to the C# code behind. This sets up a string constant to which you can refer in many places throughout your code should you need a conString in different methods.

const string CONSTRINGNAME = "conString";

4. Next add the following line of code to the C# code behind. This gets the connection string from the web.config file with the name conString (from the constant above)

ConnectionStringSettings conString = rootWebConfig.ConnectionStrings.ConnectionStrings[CONSTRINGNAME];

5. Finally, where you origionally would have had something similar to this line of code:

SqlConnection con = new SqlConnection(conString)

you will replace it with this line of code:

SqlConnection con = new SqlConnection(conString.ConnectionString)

After doing these 5 steps your code should work as it did before. Hense the reason you test the constring first in its origional format so you know if it is a problem with the connection string or if it is a problem with the code.

I am new to C#, ASP.Net and Sql Server. So I am sure there must be a better way to do this code. I also would appreicate feedback on how to improve these steps if possible. I have looked all over for something like this but I eventually figured it out after many weeks of hard work. Looking at it myself, I still think, there must be an easier way.

I hope this is helpful.


it should be within the <configuration> node:

  <connectionStrings >
    <add name="myconnectionstring" connectionString="Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;" providerName="System.Data.SqlClient"/>
  </connectionStrings>

this site has more info on it:


in header

using System.Configuration;

in code

SqlConnection conn = new SqlConnection(*ConfigurationManager.ConnectionStrings["connstrname"].ConnectionString*);

Connection in WebConfig

<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=192.168.1.25;Initial Catalog=Login;Persist Security Info=True;User ID=sa;Password=example.com"   providerName="System.Data.SqlClient" />
</connectionStrings>

In Class.Cs

public static string ConnectionString{
get{
return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;}
set{}

You can also use external configuration file to specify connection strings section, and refer that file in application configuration file like in web.config

Like the in web.config file:

<configuration>  
    <connectionStrings configSource="connections.config"/>  
</configuration>  

The external configuration connections.config file will contains connections section

<connectionStrings>  
  <add name="Name"   
   providerName="System.Data.ProviderName"   
   connectionString="Valid Connection String;" />  

</connectionStrings>  

Modifying contents of external configuration file will not restart the application (as ASP.net does by default with any change in application configuration files)


If you want to write connection string in Web.config then write under given sting

<connectionStrings>
  <add name="Conn" connectionString="Data Source=192.168.1.25;Initial Catalog=Login;Persist Security Info=True;User ID=sa;Password=example.com"
   providerName="System.Data.SqlClient" />
 </connectionStrings>

OR

you right in aspx.cs file like

SqlConnection conn = new SqlConnection("Data Source=12.16.1.25;Initial Catalog=Login;Persist Security Info=True;User ID=sa;Password=example.com");

You can put this in your web.config file connectionStrings:

<add name="myConnectionString" connectionString="Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;" providerName="System.Data.SqlClient"/>

You can use following format:

  <connectionStrings>
    <add name="ConStringBDName" connectionString="Data Source=serverpath;Initial Catalog=YourDataBaseName;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
  </connectionStrings>

Most probably you will fing connectionstring tag in web.config after <appSettings>

Try out this.


You can try this. It is very simple

<connectionStrings>         
    <add name="conString" connectionString="Data Source=SQLServerAddress;Initial Catalog=YourDatabaseName; User Id=SQLServerLoginId; Password=SQLServerPassword"/>
</connectionStrings>

Try this for your connection string.

 Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;
 User ID=myDomain\myUsername;Password=myPassword;

I JUST FOUND!! You need to put this string connection and point directly to your database. Same case on server.

"Provider=Microsoft.ACE.OLEDB.12.0; 
 Data Source=c:/inetpub/wwwroot/TEST/data/data.mdb;"

It works!! :)


Store connection string in web.config

It is a good practice to store the connection string for your application in a config file rather than as a hard coded string in your code. The way to do this differs between .NET 2.0 and .NET 3.5 (and above). This article cover both. https://www.connectionstrings.com/store-connection-string-in-webconfig/


Create a section called <connectionStrings></connectionStrings> in your web.config and add different connection strings to it, for example

 <connectionStrings>
  <add name="ConnectionStringName" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=DatabaseName;Integrated Security=True;MultipleActiveResultSets=True"/>
 </connectionStrings>

Here's a list of all the different connection string formats https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx

참고URL : https://stackoverflow.com/questions/5642474/setting-up-connection-string-in-asp-net-to-sql-server

반응형