首先,我创建了一个 WPF 应用程序和一个 SQL 数据库并成功解析/连接它们,但我的组织希望我使用从数据库连接到应用程序的连接 XML。(最好使用.System.XML.Linq)我对其进行了硬编码我基本上想用 XML 连接替换我的硬编码连接
我的 XML 的名称是 Connection.XML。XML 文件的结构是这样的。主要标签<configuration></configuration>包含<connectionString></connectionString>标签中的连接字符串。它们下面是<DataSource></DataSource>中的数据库名
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>Data Source=LAPTOP-ONETG0O\SQLEXPRESS; Initial Catalog = Login; Integrated Security = true;</connectionStrings>
<DataSource>Login</DataSource>
</configuration>
这个应用程序
公共部分类登录屏幕:窗口{
public LoginScreen()
{
InitializeComponent();
}
private void btn_Click(object sender, RoutedEventArgs e)
{
SqlConnection sqlCon = new SqlConnection(@"Data Source=LAPTOP-ONETG0O\SQLEXPRESS; 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(); }
}
}
}