c# - 我已经在我的 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(); }
}
}
}
解决方案
正如@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;
推荐阅读
- php - useFileTransport 为 false 时的 yii2 错误
- javascript - 正则表达式匹配所有字符实例,除非后跟数字或单独
- python - 如何在 Python 中“动态”分配类变量?
- sql - 为什么最新的 phpmyadmin 删除了 sql 作为导出格式?
- java - 从 txt 中读取多行 | JAVA
- ios - 音频循环后更新 nowPlayingInfo currentTime
- google-app-engine - Google App Engine柔性环境中如何设置jetty线程池
- android - 更新数据库。Sqlite-asset-helper 库
- python-2.7 - PIP 和 EASY_INSTALL 已安装但无法正常工作
- c# - esp8266和Unity之间的udp连接问题