我是 C# 的新手。我想问,如何将连接字符串配置成一个类?
因为每次想写代码,都需要重新编写连接字符串,测试连接。所以,我需要创建一个类,这样每次连接数据库时,这个类都会先测试连接。然后在它工作之后,该类会将连接字符串发送到我的编码中。 此外,如果我想更改我的源数据,我只需要在类中进行更改。无需搜索我所有的编码
因此,如果我可以上课,我该如何调用并从课程中获取连接字符串?
可以这样吗?
这是我当前在 C# 中对连接字符串的编码
FileInfo file = new FileInfo(Application.StartupPath + "\\conn.txt");
if (file.Exists)
{
StreamReader r = File.OpenText(Application.StartupPath + "\\conn.txt");
connString = r.ReadToEnd();
r.Close();
// Open SQL connection
SqlConnection openCon = new SqlConnection(connString);
try
{
Cursor = Cursors.WaitCursor;
openCon.Open();
}
catch
{
MessageBox.Show("Error to established connection\nPlease check Data Source");
openCon.Close();
Cursor = Cursors.Arrow;
}
else
{
MessageBox.Show("File config is missing");
}
}
希望你能教我作为 C# 的新手。谢谢您的帮助。抱歉英语不好。