StreamReader in class for SqlConnection
本文关键字:SqlConnection for class in StreamReader | 更新日期: 2023-09-27 18:25:12
我在课堂上有这段代码,应该从文本框中读取4行,但程序停止了,所以我不知道错误在哪里
using System.Data.SqlClient;
using System.IO;
namespace tours
{
class myConnection
{
public static SqlConnection GetConnection()
{
string path = "C:''Users''marek''Documents''Visual Studio 2012''Projects''tours''tours''sql_string.txt";
StreamReader sr = new StreamReader(File.Open(path, FileMode.Open));
while (sr.Peek() >= 0)
{
}
string str = "Data Source='" + sr.ReadLine() + "';Initial Catalog ='" + sr.ReadLine() + "' ;user='" + sr.ReadLine() + "';password= '" + sr.ReadLine() + "'";
SqlConnection con = new SqlConnection(str);
con.Open();
return con;
}
}
}
这就是我在形式中的称呼
private void nastaveni_Load(object sender, EventArgs e)
{
try
{
nacti_spojeni();
myConnection.GetConnection();
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
}
删除
//while (sr.Peek() >= 0)
//{
//}
string str = "Data Source='" + sr.ReadLine() + "';Initial Catalog ='" + sr.ReadLine() + "' ;user='" + sr.ReadLine() + "';password= '" + sr.ReadLine() + "'";
或者你可以按照下面的
var lines = File.ReadAllLines(path);
if (lines.Length >=4)
{
string str = string.Format("Data Source='{0}';Initial Catalog ='{1}' ;user='{2}';password= '{3}'"
, lines[0], lines[1], lines[2], lines[3]);
}
我不知道为什么要将连接详细信息保存在文本文件中。在.Net中,如果是web应用程序或其他应用程序配置文件,我们可以将连接字符串存储在web.config中
阅读更多信息,请查看以下链接:
http://www.connectionstrings.com/store-connection-string-in-webconfig/
http://msdn.microsoft.com/en-us/library/ms254494(v=vs.100).aspx