C# - >从SQL Server 2008中检索数据集

use*_*142 2 .net c# sql asp.net

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

//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);
}  
Run Code Online (Sandbox Code Playgroud)

这会抛出一个sql异常,

"无效的对象名称"...

我究竟做错了什么?

Chr*_*sBD 7

您没有将实际的SQL select命令传递给SqlCommand构造函数.


Ame*_*ach 7

打开连接!!!!!!

 //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);
 }  
Run Code Online (Sandbox Code Playgroud)

  • 实际上,使用`SqlDataAdapter`你**不必自己打开连接 - 适配器**将**为你做这个! (2认同)