I just want to loop through the results in the database. That’s all I am trying to do at this point! This is the error I get when I try to debug:
A network-related or instance-specific error occurred while
establishing a connection to SQL Server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections. (provider: SQL
Network Interfaces, error: 26 – Error Locating Server/Instance
Specified)
It points to this line:
// fill dataset into named table
myAdapter.Fill(myDataSet, "Sent");
Here is my whole code:
// get connection strings from app.config
string conString = ConfigurationManager.ConnectionStrings["Database1ConnectionString"].ConnectionString;
// connection object
SqlConnection myConn = new SqlConnection(conString);
// create adapter
SqlDataAdapter myAdapter = new SqlDataAdapter("select * from `Sent`", myConn);
// create command builder
SqlCommandBuilder myCommandBuilder = new SqlCommandBuilder(myAdapter);
// create dataset
DataSet myDataSet = new DataSet();
// fill dataset into named table
myAdapter.Fill(myDataSet, "Sent");
// query using linq
IEnumerable<DataRow> results
= from row in myDataSet.Tables["Sent"].AsEnumerable()
select row;
// enumerate through results
foreach (DataRow row in results)
{
MessageBox.Show(row.ToString());
}
What can I do to fix this? Also, if anyone has an easier way to use databases in C#, I am open to your ideas because this has been ridiculous for me (manipulating a database in c#). Thank you for your help.
Update 6/29/12:
The following code works for me:
// get connection strings from app.config
string conString = ConfigurationManager.ConnectionStrings["Database1ConnectionString"].ConnectionString;
// connection object
SqlCeConnection myConn = new SqlCeConnection(conString);
// create adapter
SqlCeDataAdapter myAdapter = new SqlCeDataAdapter("select * from [Sent]", myConn);
// create command builder
SqlCeCommandBuilder myCommandBuilder = new SqlCeCommandBuilder(myAdapter);
// create dataset
DataSet myDataSet = new DataSet();
// fill dataset into named table
myAdapter.Fill(myDataSet, "Sent");
// create new row
DataRow newRow = myDataSet.Tables["Sent"].NewRow();
// set field vals
newRow["sendTo"] = sendTo;
newRow["subject"] = subject;
newRow["message"] = message;
// add new row to table
myDataSet.Tables["Sent"].Rows.Add(newRow);
// update database
myAdapter.UpdateCommand = myCommandBuilder.GetUpdateCommand();
int updatedRows = myAdapter.Update(myDataSet, "Sent");
//MessageBox.Show("There were "+updatedRows.ToString()+" updated rows");
// close connection
myConn.Close();
I wasn’t using the correct code (it didn’t have anything to do with any connection stuff). This was my first crack at trying to connect to a database in a language other than PHP. Now, I would probably use LINQ or Lambda expressions than this code. But here is what I used which worked: