c# – 如何从web.config添加和访问连接字符串
发布时间:2020-12-16 01:39:21 所属栏目:百科 来源:网络整理
导读:我想添加连接字符串以连接到web.config文件中定义的 mysql并访问我的C#代码中的相同连接我该怎么办? 这是我的代码示例,在单击按钮以连接到数据库之后运行. protected void Button2_Click(object sender,EventArgs e) { String a = DropDownList1.SelectedIt
我想添加连接字符串以连接到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(); } } 解决方法
如果您知道连接字符串名称,则可以使用ConfigurationManager类的ConnectionStrings属性
例如. using System.Configuration; string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString.ToString(); 其中,您的web.config将包含名为ConnectionStringName的连接字符串 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |