Reputation: 865
I am having trubble to get the stored values from my mdf. I can see they are there and all is working as suposed to untill i a want to get hold of them, I just cant. I have been trying for almost 48h and I just cant get it to work. I read tons of guides and other threads here but nothing seems to work for me. I guess I just have get my head around this way of accessing and mdf SQL database. I just want it to give up the secrets stored on specified row.
I am trying to access the three values stored on a numbered row(specified as int row) in a mdf file called Table1 and return them to the caller.
My code I have been fighting the last hours is this:
public static void loadAnimalData(int row, out string stringId, out string name, out double age)
{
int antal = AnimalsDBCount();
String connString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|path.to.db|DBList.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlConnection con = new SqlConnection(connString);
con.Open();
using (SqlCommand command = new SqlCommand("SELECT ID WHERE ID = " + row, con))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
m_stringId = reader.GetString(0);
m_name = reader.GetString(1);
m_age = reader.GetDouble(2);
}
}
con.Close();
stringId = m_stringId;
name = m_name;
age = m_age;
}
I am lost here, I can't seem to get access to specied row or values, Where am I going wrong?
Upvotes: 1
Views: 1117
Reputation: 98740
Might you want is;
m_stringId = reader[0].ToString();
m_name = reader[1].ToString();
m_age = reader[2].ToString();
SqlDataReader
read rows, since you select one, you can't access others.
Provides a way of reading a forward-only stream of rows from a SQL Server database.
You shoudl select other columns also like;
using (SqlCommand command = new SqlCommand("SELECT ID, NAME, AGE WHERE ID = " + row, con))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
m_stringId = reader.GetInt32(0);
m_name = reader.GetString(1);
m_age = reader.GetString(2);
}
}
Upvotes: 1
Reputation: 4768
You may wish to select your columns in your select statement
using (SqlCommand command = new SqlCommand("SELECT ID, name, age from TableOfInterest WHERE ID = " + row, con))
Then you can use them in your Reader
Upvotes: 1
Reputation: 171351
You are only selecting the ID
(which is already known), not any other columns.
Try changing:
"SELECT ID WHERE ID = " + row
to
"SELECT ID, NAME, AGE WHERE ID = " + row
Upvotes: 1