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

时间:2010-11-18 05:13:56

标签: c# asp.net mysql visual-studio web-config

我想添加连接字符串以连接到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();
            }
        }

5 个答案:

答案 0 :(得分:3)

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

的ConnectionStrings属性

E.g。

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

其中,您的web.config将包含名为ConnectionStringName

的连接字符串

答案 1 :(得分:3)

以下是为SQL Server的web.config创建和添加connectionString的示例 您可以将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");

希望这将是完整的

答案 2 :(得分:1)

在网络配置中:

<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();

答案 3 :(得分:0)

在所有这些答案中static都缺失了

导入此命名空间:

using System.Configuration;

获取连接字符串:

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

答案 4 :(得分:0)

网络配置

router.post('/games/:id/verify', isAuthenticated, function(req, res){
        log('@POST verify for game with id: ' + req.params.id);
        gameController.postVerify(req.params.id, req, res);
    });

aspx页面

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