【问题标题】:C# -> Retrieving dataset from SQL Server 2008C# -> 从 SQL Server 2008 检索数据集
【发布时间】:2012-02-23 12:08:00
【问题描述】:

我的 SQL Server 数据库中有一个名为 NAMES 的表。我正在尝试检索整个表并将其放入数据集:

//get the connection string from web.config
string connString = ConfigurationManager.ConnectionStrings["Platform"].ConnectionString;
DataSet dataset = new DataSet();

using (SqlConnection conn = new SqlConnection(connString))
{
    SqlDataAdapter adapter = new SqlDataAdapter();                
    adapter.SelectCommand = new SqlCommand("NAMES", conn);
    adapter.Fill(dataset);
}  

这会抛出一个 sql 异常,

“无效的对象名称名称”...

我做错了什么?

【问题讨论】:

  • adapter.SelectCommand = new SqlCommand("select * from [NAMES]", conn);

标签: c# asp.net .net sql


【解决方案1】:

打开连接!!!!!!

 //get the connection string from web.config
 string connString = ConfigurationManager .ConnectionStrings["Platform"].ConnectionString;
 DataSet dataset = new DataSet();

 using (SqlConnection conn = new SqlConnection(connString))
 {
     SqlDataAdapter adapter = new SqlDataAdapter();                
     adapter.SelectCommand = new SqlCommand("select * from [NAMES]", conn);
     conn.Open(); 
     adapter.Fill(dataset);
 }  

【讨论】:

  • 打开连接肯定会有所帮助,但我不认为这是你会看到的例外。无效的对象名称肯定表明它已到达数据库。我假设上面的代码是一个缩减版本,只是不小心省略了数据库的打开。
  • 能否通过SQL管理工作室访问数据库,检查这张表是否真的存在
  • 实际上,使用SqlDataAdapter,您不必必须自己打开连接 - 适配器为您完成此操作!跨度>
  • 使用sqldataadapter时不打开连接,适配器自己打开和关闭连接
【解决方案2】:

您没有将实际的 SQL 选择命令传递给 SqlCommand 构造函数。

【讨论】:

  • 如果我将“NAMES”更改为“SELECT * FROM NAMES”,我仍然会遇到同样的错误
  • 您是否尝试过[NAMES](根据@AmenAyach 的建议)? Names 是一个 ODBC 保留关键字,因此在解析 SQL 时会引起潜在的混淆,除非您正确地对其进行转义。
【解决方案3】:

首先检查 Select * from dbo.[Names] 是否在你的 sql 中工作?

     string connString = ConfigurationManager .ConnectionStrings["Platform"].ConnectionString;
        Dataset ds=new Dataset();
        SqlConnection con = new Sqlconnection(connString);
        SqlDataAdapter adapter = new SqlDataAdapter("Select * from dbo.[Names]",con);
        adapter.Fill(ds);

【讨论】:

    猜你喜欢
    • 2018-09-01
    • 1970-01-01
    • 2012-11-01
    • 2014-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    相关资源
    最近更新 更多