gpt4 book ai didi

c# - WPF 中的 SQL Server 连接

转载 作者:行者123 更新时间:2023-11-30 20:02:07 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com