如何从 web.config 添加和访问连接字符串

发布于 2024-10-03 14:38:33 字数 1824 浏览 2 评论 0原文

我想添加连接字符串来连接到 web.config 文件中定义的 mysql,并在我的 C# 代码中访问相同的连接,我该怎么做?

这是我的代码示例,在单击按钮连接到数据库后运行。

protected void Button2_Click(object sender, EventArgs e)
    {
        String a = DropDownList1.SelectedItem.Value;
        String b = DropDownList3.SelectedItem.Value.PadLeft(3, '0');      
        String c = TextBox2.Text.PadLeft(5,'0').ToString();
        String d = TextBox3.Text.ToString();
        String digit = a+ b  + c + d;
        try
        {
         myConn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=testcase;User=root;Password=root;Option=3;");
         myConn.Open();
            //**
            string sql = "select * from testcase.main where reg_no =?";            
            //**
            OdbcCommand cmd = new OdbcCommand(sql, myConn);            
            //**
            cmd.Parameters.AddWithValue("?", digit);
            MyReader = cmd.ExecuteReader();
            //**
            while (MyReader.Read())
            {
                String f = MyReader["pet_name"].ToString();
                String g = MyReader["res_name"].ToString();

                Label9.Visible = true;
                Label9.Text = f;

                Label10.Visible = true;
                Label10.Text = "VS";

                //Label11.Visible = true;
                Label11.Text = g;

            }

            MyReader.Close();
        }
        catch (Exception e1)
        {
            Response.Write(e1.ToString());
        }
        finally
        {
            if (MyReader != null && !MyReader.IsClosed)
            {
                MyReader.Close();   
            }

            if (myConn != null && myConn.State == ConnectionState.Open)
            {
                myConn.Close();
            }
        }

I want to add connection string to connect to mysql that are define in web.config file and access the same connection in my C# code how can I do this?

Here is my code sample that run after onclick of a button to connect to database.

protected void Button2_Click(object sender, EventArgs e)
    {
        String a = DropDownList1.SelectedItem.Value;
        String b = DropDownList3.SelectedItem.Value.PadLeft(3, '0');      
        String c = TextBox2.Text.PadLeft(5,'0').ToString();
        String d = TextBox3.Text.ToString();
        String digit = a+ b  + c + d;
        try
        {
         myConn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=testcase;User=root;Password=root;Option=3;");
         myConn.Open();
            //**
            string sql = "select * from testcase.main where reg_no =?";            
            //**
            OdbcCommand cmd = new OdbcCommand(sql, myConn);            
            //**
            cmd.Parameters.AddWithValue("?", digit);
            MyReader = cmd.ExecuteReader();
            //**
            while (MyReader.Read())
            {
                String f = MyReader["pet_name"].ToString();
                String g = MyReader["res_name"].ToString();

                Label9.Visible = true;
                Label9.Text = f;

                Label10.Visible = true;
                Label10.Text = "VS";

                //Label11.Visible = true;
                Label11.Text = g;

            }

            MyReader.Close();
        }
        catch (Exception e1)
        {
            Response.Write(e1.ToString());
        }
        finally
        {
            if (MyReader != null && !MyReader.IsClosed)
            {
                MyReader.Close();   
            }

            if (myConn != null && myConn.State == ConnectionState.Open)
            {
                myConn.Close();
            }
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

梦言归人 2024-10-10 14:38:34

在所有这个答案中 static 缺少

导入此命名空间:

using System.Configuration;

获取连接字符串:

static string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString.ToString();

In all this answer static is missing

import this namespace:

using System.Configuration;

Get connection string:

static string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString.ToString();
离旧人 2024-10-10 14:38:34

网络配置

<connectionStrings>   
     <add name="cn"connectionString="server=localhost;database=database_name;uid=username;password=your password"/> 
</connectionStrings>

aspx页面

string constr=ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
MySqlConnection con = new MySqlConnection(constr);
MySqlCommand cmd =new MySqlCommand("select * from  tbl_mastercampaign", con);

web config

<connectionStrings>   
     <add name="cn"connectionString="server=localhost;database=database_name;uid=username;password=your password"/> 
</connectionStrings>

aspx page

string constr=ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
MySqlConnection con = new MySqlConnection(constr);
MySqlCommand cmd =new MySqlCommand("select * from  tbl_mastercampaign", con);
不语却知心 2024-10-10 14:38:33

的 ConnectionStrings 属性

如果您知道连接字符串名称,则可以使用 ConfigurationManager

using System.Configuration;
string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString.ToString();

其中,您的 web.config 将包含名为 ConnectionStringName 的连接字符串

If you know the connection string name you can use the ConnectionStrings property of the ConfigurationManager class

E.g.

using System.Configuration;
string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString.ToString();

Where, your web.config would contain a connectionstring named ConnectionStringName

赴月观长安 2024-10-10 14:38:33

以下是为 SQL Server 创建连接字符串并将其添加到 web.config 的示例
您可以将 sql 连接更改为 OleDb 连接

SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder();
        connectionStringBuilder.DataSource = "localhost";
        connectionStringBuilder.IntegratedSecurity = true;
        connectionStringBuilder.InitialCatalog = "SampleDB";

        ConnectionStringSettings connSttng = new ConnectionStringSettings();
        connSttng.Name = "ConnectionStringName";
        connSttng.ProviderName = "Providername";
        connSttng.ConnectionString = String.Format("DataSource={0};InitialCatalog={1};IntegratedSecurity={2}", connectionStringBuilder.DataSource, connectionStringBuilder.InitialCatalog, connectionStringBuilder.IntegratedSecurity);

        Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
        config.ConnectionStrings.ConnectionStrings.Add(connSttng);
        config.Save(ConfigurationSaveMode.Modified, true);
        ConfigurationManager.RefreshSection("connectionStrings");

希望这将是完整的

Here is an Example of Creating and adding connectionString to the web.config for SQL Server
you can change the sql Connection to OleDb connection

SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder();
        connectionStringBuilder.DataSource = "localhost";
        connectionStringBuilder.IntegratedSecurity = true;
        connectionStringBuilder.InitialCatalog = "SampleDB";

        ConnectionStringSettings connSttng = new ConnectionStringSettings();
        connSttng.Name = "ConnectionStringName";
        connSttng.ProviderName = "Providername";
        connSttng.ConnectionString = String.Format("DataSource={0};InitialCatalog={1};IntegratedSecurity={2}", connectionStringBuilder.DataSource, connectionStringBuilder.InitialCatalog, connectionStringBuilder.IntegratedSecurity);

        Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
        config.ConnectionStrings.ConnectionStrings.Add(connSttng);
        config.Save(ConfigurationSaveMode.Modified, true);
        ConfigurationManager.RefreshSection("connectionStrings");

Hope this will be use full

不打扰别人 2024-10-10 14:38:33

在网络配置中:

<connectionStrings>
<add 
    name="NorthwindConnectionString"
    connectionString="Data Source=serverName;Initial 
    Catalog=Northwind;Persist Security Info=True;User
    ID=userName;Password=password"
    providerName="System.Data.SqlClient"/>
 </connectionStrings>

在视图中:

using System.Configuration;
string ConnectionString =ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString.ToString();

in web config:

<connectionStrings>
<add 
    name="NorthwindConnectionString"
    connectionString="Data Source=serverName;Initial 
    Catalog=Northwind;Persist Security Info=True;User
    ID=userName;Password=password"
    providerName="System.Data.SqlClient"/>
 </connectionStrings>

in view:

using System.Configuration;
string ConnectionString =ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString.ToString();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文