首页 > 解决方案 > 我已经在我的 SQL 数据库和 WPF 应用程序之间创建了一个连接,但我想使用 XML 文件和 XDocument 来连接它们

问题描述

首先,我创建了一个 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(); }
    }
    
       
    }

}

标签: c#xmlwpflinq-to-xml

解决方案


正如@Charlieface 提到的,连接通常在应用程序的配置 XML 文件中处理。在这里查看:App.Config:基础知识和最佳实践

回到您定制的 XML 文件。通过 LINQ to XML 很简单。

XML 文件

<?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>

C#

void Main()
{
    const string FILENAME = @"e:\Temp\Connection.xml";

    XDocument xdoc = XDocument.Load(FILENAME);
    string conn = xdoc.Descendants("connectionStrings").FirstOrDefault().Value;
    
    Console.WriteLine("ConnectionString: {0}", conn);
}

输出

ConnectionString: Data Source=LAPTOP-ONETG0O\SQLEXPRESS; Initial Catalog = Login; Integrated Security = true;

推荐阅读