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

I've created a connection between my SQL database and a WPF App but i want use an XML file and XDocument to connect them

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

替换我的硬编码连接

我的 XML 的名字是 Connection.XML。 XML 文件的结构如此。主要标签 包含 > /connectionString> 标签中的连接字符串。它们下面是>/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 部分 class 登录屏幕:Window {

    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(); }
    }
    
       
    }

}

如@Charlieface 所述,连接通常在应用程序的配置XML 文件中处理。在这里查看:App.Config: Basics and Best Practices

返回您定制的 XML 文件。通过 LINQ 到 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;