I’m trying to learn how to connect to an SQL Server database (I’m using the AdventureWorks sample database), but I’m having problems.
Here’s the code I’m using:
// define connection string for database server
string connectionString = "server=<server name>; database=AdventureWorks; uid=<user name>; pwd=;"; // no password
// define SqlConnection connection to database using connection string
SqlConnection conn = null;
try
{
conn = new SqlConnection (connectionString);
}
catch (Exception exc)
{
MessageBox.Show (exc.Message, "conn = new SqlConnection (connectionString);");
}
// define SqlCommand command or command string that contains query
string commandString = "SELECT * from <table name>";
// define SqlDataAdapter data adapter using command string & connection object:
SqlDataAdapter dataAdapter = new SqlDataAdapter (commandString, conn);
// create new DataSet object (create DataSet)
DataSet ds = new DataSet ();
try
{ // fill dataset object with query result via data adapter (for SELECT)
dataAdapter.Fill (ds, "<table name>");
}
catch (Exception exc)
{
MessageBox.Show (exc.Message, "dataAdapter.Fill (ds, \"<table name>\");");
}
// result of query now stored in dataset object in table "<table name>"
// get reference to table by using indexer property of dataset object's Tables collection
dataTable = ds.Tables ["<table name>"];
At the statement
dataAdapter.Fill (ds, "<table name>");
I'm getting the following error: "Login failed for user '<my user name>'."
As near as I can make out, the database AdventureWorks that I see in SQL Server 2008 Management Studio and that I'm trying to access resides at either C:\Program Files\Microsoft SQL Server\100\Tools\Samples\AdventureWorks 2008 OLTP or
C:\Program Files\Microsoft SQL Server\100\Tools\Samples\AdventureWorks OLTP.
I thought that maybe the problem was I was supposed to specify the full path name in the connection string, but that didn't help. Any suggestions?