I'我在SQL数据库和WPF应用程序之间创建了一个连接,但我想使用XML文件和XDocument来连接它们



首先,我创建了一个WPF应用程序和一个SQL数据库,并成功地解析/连接了它们,但我的组织希望我使用从数据库连接到应用程序的连接XML。(最好使用.System.XML.Linq(我对它进行了硬编码,我基本上想用XML连接代替我的硬编码连接

我的XML的名称是Connection。XML。XML文件的结构是这样的;配置>lt;/配置>在<connectionString>lt/connectionString>标签。它们下面是<数据源>lt/数据源>

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>Data Source=LAPTOP-ONETG0OSQLEXPRESS; Initial Catalog = Login; Integrated Security = true;</connectionStrings> 
<DataSource>Login</DataSource> 
</configuration>

这是应用

公共分部类LoginScreen:窗口{

public LoginScreen()
{
InitializeComponent();

}


private void btn_Click(object sender, RoutedEventArgs e)
{
SqlConnection sqlCon = new SqlConnection(@"Data Source=LAPTOP-ONETG0OSQLEXPRESS; Initial Catalog = Login; Integrated Security = true");
try
{
if (sqlCon.State == ConnectionState.Closed)
sqlCon.Open();
String query = "SELECT COUNT(1) FROM tblUSER WHERE Username=@UserName AND Password=@Password";
SqlCommand sqlCmd = new SqlCommand(query, sqlCon);
sqlCmd.CommandType = CommandType.Text;
sqlCmd.Parameters.AddWithValue("@Username", txtUserName.Text);
sqlCmd.Parameters.AddWithValue("@Password", txtPassWord.Password);
int count = Convert.ToInt32(sqlCmd.ExecuteScalar());
if (count == 1)
{
MainWindow dashboard = new MainWindow();
dashboard.Show();
this.Close();
}
else
{
MessageBox.Show("Username or password is incorrect");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally { sqlCon.Close(); }
}


}

}

正如@Charlieface所提到的,连接通常在应用程序的配置XML文件中处理。点击此处查看:应用程序。配置:基础和最佳实践

返回到您的自定义XML文件。通过LINQ to XML,这是微不足道的。

XML文件

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>Data Source=LAPTOP-ONETG0OSQLEXPRESS; Initial Catalog = Login; Integrated Security = true;</connectionStrings>
<DataSource>Login</DataSource>
</configuration>

c#

void Main()
{
const string FILENAME = @"e:TempConnection.xml";
XDocument xdoc = XDocument.Load(FILENAME);
string conn = xdoc.Descendants("connectionStrings").FirstOrDefault().Value;

Console.WriteLine("ConnectionString: {0}", conn);
}

输出

ConnectionString: Data Source=LAPTOP-ONETG0OSQLEXPRESS; Initial Catalog = Login; Integrated Security = true;

最新更新