C# -> Retrieving dataset from SQL Server 2008
17,133
Solution 1
Open the connection !!!!!!
//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);
}
Solution 2
You're not passing an actual SQL select command to the SqlCommand
constructor.
Author by
user559142
Updated on June 14, 2022Comments
-
user559142 almost 2 years
I have a table called
NAMES
in my SQL Server database. I am trying to retrieve the entire table and put it into a dataset://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); }
This throws a sql exception though,
"Invalid Object Name NAMES"...
What am I doing wrong?
-
Amen Ayach about 12 yearsadapter.SelectCommand = new SqlCommand("select * from [NAMES]", conn);
-
-
user559142 about 12 yearsif I change "NAMES" to "SELECT * FROM NAMES" I still get the same error
-
Chris about 12 yearsopening the connection would certainly help but I don't think that is the exception you'd see. Invalid object name certainly suggests that it had reached the database. I assume the code above is a cut down version that just accidentally omitted the DB opening.
-
Chris about 12 yearsHave you tried
[NAMES]
instead (as per @AmenAyach's suggestion)? Names is an ODBC reserved keyword and is thus goign to cause potential confusion in parsing SQL unless you escape it properly. -
Amen Ayach about 12 yearsCan you access the database through SQL management studio to check if this table really exists
-
marc_s about 12 yearsActually, using the
SqlDataAdapter
you don't have to open the connection yourself - the adapter will do this for you! -
Alex about 12 yearswhen using sqldataadapter you don't open the connection, the adapter opens and close the connection by itself