The comments are completely correct. There is a particular sequence of events you need to do to interact with a database. I keep a piece of code on a scratch pad because I use it so much which outlines the basic structure of what you need to be doing.
using(var conn = new SqlConnection(<connection string here>))
{
try
{
conn.Open();
string sql = "<sql query here>";
using(var cmd = new SqlCommand(sql,conn))
{
using(var reader = cmd.ExecuteReader())
{
if(reader.HasRows)
{
while(reader.Read())
{
//Here is where you get your data..
int imReadingAnInt = (int)reader["myIntColumnHeader"];
string imReadingAString = reader["myStringColumnHeader"].ToString();
}
}
}
}
}
catch (Exception ex)
{
string err = ex.Message;
}
}
On inserts:
You can draft a sql insert using the above method, and use cmd.ExecuteNonQuery()
to perform the insert. An Example..
using(var conn = new SqlConnection(<connection string here>))
{
try
{
conn.Open();
string sql = "insert into [table_name] values (@column1Value,@column2Value,...);";
using(var cmd = new SqlCommand(sql,conn))
{
cmd.Parameters.AddWithValue("@column1Value",1);//Presuming column 1 is an int
cmd.Parameters.AddWithValue("@column2Value","Smith"); //Presuming column 2 is a varchar (string)
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
string err = ex.Message;
}
}
Note the above code uses paramaterization (sp) to prevent SQL injection. You could hard code the values into the SQL Query string, but it is not considered best practices from a security standpoint.
W3 Schools SQL Insert
My brain keeps churning on this.. Just a note on the fundamental concepts here. With the Objects SqlConnection, SqlCommand etc, you are not actually establishing direct access to the database (ie you can't just go grab a row and manually edit it). Instead, you are setting up a connection through which you can perform SQL queries which are a well structured method of reading and editing the database. There is of course tons of information out there on how to construct said queries, so once you understand the purpose of the C# objects in question, accessing and changing a database will make a lot more sense.