www,aavv5,cnm:asp.net中连接数据库的问题
来源:百度文库 编辑:高考问答 时间:2024/07/03 09:46:13
dim conn as sqlconnection=new sqlconnection("data source=DB; user id=test; password=test")
以上是我定义的一个数据库连接
现在要求后面的那段string,即“data source=DB; user id=test; password=test”,从配置文件(如1.txt)中读入,应该怎样写代码?
以上是我定义的一个数据库连接
现在要求后面的那段string,即“data source=DB; user id=test; password=test”,从配置文件(如1.txt)中读入,应该怎样写代码?
Dim TheFileR As System.IO.StreamReader
Dim ConnStr As String
TheFileR = System.IO.File.OpenText("1.txt")
ConnStr = TheFileR.ReadToEnd
TheFileR.Close()
dim conn as sqlconnection=new sqlconnection(ConnStr)
其中1.txt中的内容是:
"data source=DB; user id=test; password=test"
当然,最好的方式还是写到web.config中,然后用ConfigurationSettings.GetConfig("appSettings")获取使用。
建议直接存到 web.config中,
<appSettings>
<add key="ConnectionString" value="data source=DB; user id=test; password=test" />
</appSettings>
读取
NameValueCollection configSettings = (NameValueCollection) ConfigurationSettings.GetConfig("appSettings");
configSettings["ConnectionString"];