c# - WPF 中的 SQL Server 连接

标签 c# sql-server

我在 SQL Server 2008 中有一个数据库并将其连接到 WPF 应用程序中。我想从表中读取数据并显示在 datagrid 中。连接已成功创建,但是当我在网格中显示它时,它显示数据库错误(异常处理)。 这就是我正在做的。提前致谢。

  try
  {
       SqlConnection thisConnection = new SqlConnection(@"Server=(local);Database=Sample_db;Trusted_Connection=Yes;");
       thisConnection.Open();

       string Get_Data = "SELECT * FROM emp";     

       SqlCommand cmd = new SqlCommand(Get_Data);              
       SqlDataAdapter sda = new SqlDataAdapter(cmd);               
       DataTable dt = new DataTable("emp");
       sda.Fill(dt);
       MessageBox.Show("connected");
       //dataGrid1.ItemsSource = dt.DefaultView;           
  }
  catch
  {
       MessageBox.Show("db error");
  }

当我注释行 sda.Fill(dt);

时,它显示 connected

最佳答案

您的 SqlCommand 不知道您打开了连接 - 它需要 SqlConnection 的实例。

try
{
       SqlConnection thisConnection = new SqlConnection(@"Server=(local);Database=Sample_db;Trusted_Connection=Yes;");
       thisConnection.Open();

       string Get_Data = "SELECT * FROM emp";     

       SqlCommand cmd = thisConnection.CreateCommand();
       cmd.CommandText = Get_Data;

       SqlDataAdapter sda = new SqlDataAdapter(cmd);               
       DataTable dt = new DataTable("emp");
       sda.Fill(dt);

       dataGrid1.ItemsSource = dt.DefaultView;           
}
catch
{
       MessageBox.Show("db error");
}

关于c# - WPF 中的 SQL Server 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17168060/

相关文章:

c# - ASP.NET 核心 2.0 : Authenticate a route without a controller

c# - 如何在 C# 中创建 JSONArray 并将该数据发送到 Android 应用程序

php - CodeIgniter 中的 MSSQL 查询

c# - 后台工作人员更新用户界面上的日志

c# - 在 C# 中使用接口(interface)作为 "out"参数

c# - 如何使用 C# 从数据库打印(在打印机上)表

sql-server - sql server在不匹配时合并多个插入

java - 在 Ubuntu Linux 上使用 LDAP 连接到 MSSQL 服务器

sql - 如何从数据库表中选择 4 个大小相等的结果集

sql - 在 SQL Server 中格式化时间?