简体   繁体   English

在 ASP.NET 中设置连接字符串到 SQL SERVER

[英]Setting up connection string in ASP.NET to SQL SERVER

I'm trying to set up a connecting string in my web.config file (Visual Studio 2008/ASP.NET 3.5) to a local server (SQL server 2008).我正在尝试在我的 web.config 文件(Visual Studio 2008/ASP.NET 3.5)中设置一个连接到本地服务器(SQL server 2008)的字符串。

In my web.config, how and where do I place the connection string?在我的 web.config 中,如何以及在哪里放置连接字符串?

Here's what web.config file looks like right now: http://imwired.net/aspnet/Online_web.config这是 web.config 文件现在的样子: http : //imwired.net/aspnet/Online_web.config

You can also use this, it's simpler.你也可以使用这个,它更简单。 The only thing you need to set is "YourDataBaseName".您唯一需要设置的是“YourDataBaseName”。

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

Where to place the connection string在哪里放置连接字符串

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

For some reason I don't see the simple answer here.出于某种原因,我在这里看不到简单的答案。

Put this at the top of your code:把它放在你的代码的顶部:

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

Put this in Web.Config:把它放在 Web.Config 中:

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

and where you want to setup the connection variable:以及您想要设置连接变量的位置:

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

I found this very difficult to get an answer to but eventually figured it out.我发现这很难得到答案,但最终想通了。 So I will write the steps below.所以我会写下面的步骤。

  1. Before you setup your connection string in code, ensure you actually can access your database.在代码中设置连接字符串之前,请确保您确实可以访问您的数据库。 Start obviously by logging into the database server using SSMS (Sql Server Management Studio or it's equivalent in other databases) locally to ensure you have access using whatever details you intend to use.首先在本地使用 SSMS(Sql Server Management Studio 或其他数据库中的等价物)登录数据库服务器,以确保您可以使用您打算使用的任何详细信息进行访问。

  2. Next (if needed), if you are trying to access the database on a separate server, ensure you can do likewise in SSMS.接下来(如果需要),如果您尝试访问单独服务器上的数据库,请确保您可以在 SSMS 中执行同样的操作。 So setup SSMS on a computer and ensure you can access the server with the username and password to that database server.因此,在计算机上设置 SSMS 并确保您可以使用该数据库服务器的用户名和密码访问服务器。

If you don't get the above 2 right, you are simply wasting your time as you cant access the database.如果您没有正确理解上述 2 点,那么您只是在浪费时间,因为您无法访问数据库。 This can either be because the user you setup is wrong, doesn't have remote access enabled (if needed), or the ports are not opened (if needed), among many other reasons but these being the most common.这可能是因为您设置的用户错误,没有启用远程访问(如果需要),或者端口没有打开(如果需要),以及许多其他原因,但这些是最常见的。

Once you have verified that you can access the database using SSMS.一旦您确认您可以使用 SSMS 访问数据库。 The next step, just for the sake of automating the process and avoiding mistakes, is to let the system do the work for you.下一步,只是为了自动化流程和避免错误,让系统为您完成工作。

  1. Start up an empty project, add your choice of Linq to SQL or Dataset (EF is good but the connection string is embedded inside of an EF con string, I want a clean one), and connect to your database using the details verified above in the con string wizzard.启动一个空项目,将您选择的 Linq 添加到 SQL 或数据集(EF 很好,但连接字符串嵌入在 EF con 字符串中,我想要一个干净的),然后使用上面验证的详细信息连接到您的数据库con string 巫师。 Add any table and save the file.添加任何表并保存文件。

Now go into the web config, and magically, you will see nice clean working connection string there with all the details you need.现在进入 web 配置,神奇的是,你会在那里看到漂亮干净的工作连接字符串,其中包含你需要的所有细节。


{ Below was part of an old post so you can ignore this, I leave it in for reference as its the most basic way to access the database from only code behind. { 以下是旧帖子的一部分,因此您可以忽略这一点,我将其留作参考,因为它是仅从后面的代码访问数据库的最基本方法。 Please scroll down and continue from step 2 below.请向下滚动并从下面的第 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.确保您实际上可以使用某种形式的 sql 命令文本访问您的数据,该文本以标签或文本 boses 或其他形式显示表中的一些数据,因为这是执行连接字符串的最简单方法。

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: 1. 将您的字符串文字(引号中的内容,包括引号)导出到 web.config 文件的以下部分(对于多个连接字符串,只需执行多行:

<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. { 以上是旧帖的一部分,做完前3个步骤后,整个过程将为您完成,因此您可以忽略它。 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 (ie not inside a method). 2. 现在将以下代码行添加到后面的 C# 代码中,最好是在类定义下面(即不在方法内部)。 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.这通常是 web.config 文件的位置(在这种情况下,我的项目称为 MyProject。

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

3. Now add the following line of code to the C# code behind. 3. 现在将下面这行代码添加到后面的 C# 代码中。 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.这将设置一个字符串常量,如果您需要在不同方法中使用 conString,您可以在整个代码的许多地方引用该常量。

const string CONSTRINGNAME = "conString";

4. Next add the following line of code to the C# code behind. 4.接下来将下面这行代码添加到后面的C​​#代码中。 This gets the connection string from the web.config file with the name conString (from the constant above)这从名为 conString 的 web.config 文件中获取连接字符串(来自上面的常量)

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

5. Finally, where you origionally would have had something similar to this line of code: 5. 最后,你原本会有类似于这行代码的东西:

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.完成这 5 个步骤后,您的代码应该可以像以前一样工作。 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.我是 C#、ASP.Net 和 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:它应该在<configuration>节点内:

  <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:这个网站有更多关于它的信息:

Connection in WebConfig WebConfig 中的连接

Add the your connection string to the <connectionStrings> element in the Web.config file.将您的连接字符串添加到Web.config文件中的<connectionStrings>元素。

<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在 Class.Cs

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

in header在标题中

using System.Configuration;

in code在代码中

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

You can also use external configuration file to specify connection strings section, and refer that file in application configuration file like in web.config您还可以使用外部配置文件来指定连接字符串部分,并在应用程序配置文件中引用该文件,如web.config

Like the in web.config file:就像在web.config文件中:

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

The external configuration connections.config file will contains connections section外部配置connections.config文件将包含连接部分

<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)修改外部配置文件的内容不会重新启动应用程序(正如 ASP.net 在应用程序配置文件中的任何更改默认情况下所做的那样)

你可以把它放在你的web.config文件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>很可能你会在<appSettings>之后在 web.config 中找到 connectionstring 标签

Try out this.试试这个。

If you want to write connection string in Web.config then write under given sting如果要在 Web.config 中写入连接字符串,则在给定的字符串下写入

<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你就在 aspx.cs 文件中

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 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在 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). .NET 2.0 和 .NET 3.5(及更高版本)执行此操作的方法有所不同。 This article cover both.这篇文章涵盖了两者。 https://www.connectionstrings.com/store-connection-string-in-webconfig/ https://www.connectionstrings.com/store-connection-string-in-webconfig/

Create a section called <connectionStrings></connectionStrings> in your web.config inside <configuration></configuration> then add different connection strings to it, for example<configuration></configuration>内的web.config创建一个名为<connectionStrings></connectionStrings> ,然后向其中添加不同的连接字符串,例如

<configuration>

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

</configuration>

Here's a list of all the different connection string formats https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx这是所有不同连接字符串格式的列表https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM