SqlDataAdapter does not fill DataSet

与世无争的帅哥 提交于 2020-01-11 07:03:08

问题


I'm using VS2012 and SQL Server Express 2008. I've boiled down my connection/query to try and find out why my DataSet is not being filled. The connection is completed successfully, and no exceptions are thrown, but the adapter does not fill the DataSet. The database that this is pulling from is on the same PC and using localhost\SQLEXPRESS does not change the result. Thanks for any input!

SqlConnection questionConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
questionConnection.Open();
String sql = "SELECT * FROM HRA.dbo.Questions";
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
SqlCommand command = new SqlCommand(sql, questionConnection);
adapter.SelectCommand = command;
adapter.Fill(ds);
adapter.Dispose();
command.Dispose();
questionConnection.Close();

Connection String:

<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=CODING-PC\SQLEXPRESS;Initial Catalog=HRA;User ID=sa; Password= TEST" />

回答1:


try this:

SqlConnection questionConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
questionConnection.Open();
DataSet ds = new DataSet();
String sql = "SELECT * FROM HRA.dbo.Questions";
SqlDataAdapter adapter = new SqlDataAdapter(sql, questionConnection);
adapter.Fill(ds);

adapter.Dispose();
command.Dispose();
questionConnection.Close();



回答2:


It appears the answer has already been found, however, I am posting one anyway to advocate the use of using blocks, and also letting the .NET framework do the hardwork for you. Your 11 lines of code can be rewritten in 3:

DataSet ds = new DataSet();
using (var adapter = new SqlDataAdapter("SELECT * FROM HRA.dbo.Questions", ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
    adapter.Fill(ds);
}



回答3:


Is "HRA.dbo.Questions" an actual table?

Your connectionstring contains an Initial Catalog with value "HRA", and the SQL should only contain dbo.Questions as far as I know.



来源:https://stackoverflow.com/questions/13138615/sqldataadapter-does-not-fill-dataset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!