Reputation: 2021
I am developing a web application and in the code-behind, I need to get the ID column from specific table in the database and convert it to int. The query is:
string quizID = SELECT MIN(column_name) FROM table_name
and I want to put the value of it in
int quizid
which means I need to conversion, so how to do that?
Upvotes: 1
Views: 5017
Reputation: 6578
You're going to want to do something like this:
using (SqlConnection conn=new SqlConnection(sql_string)) {
conn.Open();
SqlCommand command=new SqlCommand(
sql_query,
conn
);
Int32 quizid=((Int32?)command.ExecuteScalar()) ?? 0;
}
Upvotes: 3
Reputation: 2645
SqlCommand cmd = new SqlCommand("SELECT MIN(column_name) FROM table_name", conn);
try
{
conn.Open();
int quizid = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
conn is the SqlConnection object
Upvotes: 2
Reputation: 30097
int quizID = -1;
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
string cmdText = "SELECT MIN(column_name) FROM table_name";
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
SqlDataReader reader = cmd.ExecuteReader();
if (reader != null)
{
while (reader.Read())
{
quizID = reader.GetInt32("columnname");
}
}
reader.Close();
}
conn.Close();
}
Upvotes: 3