使用 Web.Config 来设置我的 SQL 数据库连接字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1355472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 03:24:16  来源:igfitidea点击:

Using the Web.Config to set up my SQL database connection string?

asp.netsqlsql-serversql-server-2008web-config

提问by Sergio Tapia

Can anyone help me out please? I'm confused.

有人可以帮我吗?我糊涂了。

I want to set up my connection string so I can just call it from my Web.Config file.

我想设置我的连接字符串,这样我就可以从我的 Web.Config 文件中调用它。

I need a way to call it from my code, please make a little example. :(

我需要一种从我的代码中调用它的方法,请举一个小例子。:(

I also need help on setting up the Web.Config file.

我还需要有关设置 Web.Config 文件的帮助。

I don't know what properties to use. Here's a screenshot of what my credentials are. I have no password set up for Windows. I'm really lost here.

我不知道要使用什么属性。这是我的凭据的屏幕截图。我没有为 Windows 设置密码。我真的迷路了。

alt text

替代文字

回答by Rex M

Here's a great overview on MSDNthat covers how to do this.

这是MSDN 上的一个很好的概述,涵盖了如何做到这一点。

In your web.config, add a connection string entry:

在您的 web.config 中,添加一个连接字符串条目:

<connectionStrings>
  <add 
    name="MyConnectionString" 
    connectionString="Data Source=sergio-desktop\sqlexpress;Initial 
    Catalog=MyDatabase;User ID=userName;Password=password"
    providerName="System.Data.SqlClient"
  />
</connectionStrings>

Let's break down the component parts here:

让我们在这里分解组成部分:

Data Sourceis your server. In your case, a named SQL instance on sergio-desktop.

数据源是您的服务器。在您的情况下,sergio-desktop.

Initial Catalogis the default database queries should be executed against. For normal uses, this will be the database name.

初始目录是应该对其执行的默认数据库查询。对于正常使用,这将是数据库名称。

For the authentication, we have a few options.

对于身份验证,我们有几个选项。

User IDand Passwordmeans using SQL credentials, not Windows, but still very simple - just go into your Security section of your SQL Server and create a new Login. Give it a username and password, and give it rights to your database. All the basic dialogs are very self-explanatory.

用户 ID密码意味着使用 SQL 凭据,而不是 Windows,但仍然非常简单 - 只需进入 SQL Server 的安全部分并创建一个新的登录。给它一个用户名和密码,并给它访问你的数据库的权限。所有的基本对话框都是不言自明的。

You can also use integrated security, which means your .NET application will try to connect to SQL using the credentials of the worker process. Check here for more infoon that.

您还可以使用集成安全性,这意味着您的 .NET 应用程序将尝试使用工作进程的凭据连接到 SQL。请点击这里获取更多信息上。

Finally, in code, you can get to your connection string by using:

最后,在代码中,您可以使用以下命令获取连接字符串:

ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString

回答by Sergio Tapia

http://www.connectionstrings.comis a site where you can find a lot of connection strings. All that you need to do is copy-paste and modify it to suit your needs. It is sure to have all the connection strings for all of your needs.

http://www.connectionstrings.com是一个可以找到大量连接字符串的站点。您需要做的就是复制粘贴并修改它以满足您的需要。它肯定具有满足您所有需求的所有连接字符串。

回答by Sergio Tapia

Add this to your web config and change the catalog name which is your database name:

将此添加到您的 Web 配置并更改目录名称,即您的数据库名称:

  <connectionStrings>
    <add name="MyConnectionString" connectionString="Data Source=SERGIO-DESKTOP\SQLEXPRESS;Initial Catalog=YourDatabaseName;Integrated Security=True;"/></connectionStrings>

Reference System.Configuration assembly in your project.

在您的项目中参考 System.Configuration 程序集。

Here is how you retrieve connection string from the config file:

以下是从配置文件中检索连接字符串的方法:

System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

回答by Nilesh Umaretiya

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class form_city : System.Web.UI.Page
{
    connection con = new connection();
    DataTable dtable;
    string status = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        TextBoxWatermarkExtender1.WatermarkText = "Enter State Name !";        
        if (!IsPostBack)
        {
            status = "Active";
            fillgrid();
            Session.Add("ope", "Listing");
        }
    }
    protected void fillgrid()
    {
        //Session.Add("ope", "Listing");
        string query = "select *";
        query += "from State_Detail where Status='" + status + "'";
        dtable = con.sqlSelect(query);
        grdList.DataSource = dtable;
        grdList.DataBind();
        lbtnBack.Visible = false;
    }
    protected void grdList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdList.PageIndex = e.NewPageIndex;
        string operation = Session["ope"].ToString();
        if (operation == "ViewLog")
            status = "Inactive";
        else if (operation == "Listing")
            status = "Active";
        fillgrid();
    }
    public string GetImage(string status)
    {
        if (status == "Active")
            return "~/images/green_acti.png";
        else
            return "~/images/red_acti.png";
    }
    protected void grdList_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string st = "Inactive";
        int State_Id = Convert.ToInt32(grdList.DataKeys[e.RowIndex].Values[0]);
        string query = "update State_Detail set Status='" + st + "'";
        query += " where State_Id=" + State_Id;
        con.sqlInsUpdDel(query);
        status = "Active";
        fillgrid();
    }    
    protected void grdList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Select"))
        {
            string query = "select * ";
            query += "from State_Detail where State_Id=" + e.CommandArgument;
            dtable = con.sqlSelect(query);
            grdList.DataSource = dtable;
            grdList.DataBind();
            lbtnBack.Visible = true;
        }
    }
    protected void ibtnSearch_Click(object sender, ImageClickEventArgs e)
    {
        Session.Add("ope", "Listing");
        if (txtDepId.Text != "")
        {
            string query = "select * from State_Detail where State_Name like '" + txtDepId.Text + "%'";
            dtable = con.sqlSelect(query);
            grdList.DataSource = dtable;
            grdList.DataBind();
            txtDepId.Text = "";
        }
    }
    protected void grdList_RowEditing(object sender, GridViewEditEventArgs e)
    {
        int State_Id = Convert.ToInt32(grdList.DataKeys[e.NewEditIndex].Values[0]);
        Session.Add("ope", "Edit");
        Session.Add("State_Id", State_Id);
        Response.Redirect("form_state.aspx");
    }

    protected void grdList_Sorting(object sender, GridViewSortEventArgs e)
    {
        string operation = Session["ope"].ToString();
        if (operation == "ViewLog")
            status = "Inactive";
        else if (operation == "Listing")
            status = "Active";

        string query = "select * from State_Detail";
        query += " where Status='" + status + "'";
        dtable = con.sqlSelect(query);
        DataView dview = new DataView(dtable);
        dview.Sort = e.SortExpression + " asc";
        grdList.DataSource = dview;
        grdList.DataBind();
    }
}
<asp:Image ID="imgGreenAct" ImageUrl='<%# GetImage(Convert.ToString(DataBinder.Eval(Container.DataItem, "Status")))%>' AlternateText='<%# Bind("Status") %>' runat="server" />

回答by Fergal Mohan

If you use the Connect to Database under tools in Visual Studio, you will be able to add the name of the Server and database and test the connection. Upon success you can copy the string from the bottom of the dialog.

如果使用 Visual Studio 中工具下的 Connect to Database,您将能够添加服务器和数据库的名称并测试连接。成功后,您可以从对话框底部复制字符串。

回答by Eric

Your best bet, starting fresh like you are, is to go grab the enterprise library. They have a configuration tool you can use to wire everything up for you nicely.

你最好的选择,像你一样重新开始,是去获取企业库。他们有一个配置工具,你可以用它来为你很好地连接一切。

They also have a data access application block which is very useful and documentation filled with good samples.

他们还有一个非常有用的数据访问应用程序块,并且文档中充满了很好的示例。

http://www.microsoft.com/downloads/details.aspx?FamilyId=90DE37E0-7B42-4044-99BE-F8ECFBBC5B65&displaylang=en

http://www.microsoft.com/downloads/details.aspx?FamilyId=90DE37E0-7B42-4044-99BE-F8ECFBBC5B65&displaylang=en

回答by waqasahmed

If you are using SQL Express (which you are), then your login credentials are .\SQLEXPRESS

如果您使用的是 SQL Express(您是),那么您的登录凭据是 .\SQLEXPRESS

Here is the connectionString in the web config file which you can add:

这是您可以添加的 web 配置文件中的 connectionString:

<connectionStrings>
<add connectionString="Server=localhost\SQLEXPRESS;Database=yourDBName;Initial Catalog= yourDBName;Integrated Security=true" name="nametoCallBy" providerName="System.Data.SqlClient"/>
</connectionStrings>

Place is just above the system.web tag.

位置就在 system.web 标签上方。

Then you can call it by:

然后你可以通过以下方式调用它:

connString = ConfigurationManager.ConnectionStrings["nametoCallBy"].ConnectionString;

回答by user2959576

Web.config file

Web.config 文件

<connectionStrings>
  <add name="MyConnectionString" connectionString="Data Source=SERGIO-DESKTOP\SQLEXPRESS;    Initial Catalog=YourDatabaseName;Integrated Security=True;"/>
</connectionStrings>

.cs file

.cs 文件

System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;