How do i know whether the connection is open with the sqlserver database while work in the application?
You should always open a connection explicity so if the Open method does not fail, you can assume it is open. It's best to wrap your connections in using statements like the following.
public int GetUserIdFromUserName(string userName)
{
int userId = -1;
using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["knovoloCMS"].ConnectionString))
{
sqlConnection.Open();
try
{
String SqlDeleteString = @."
SELECT id FROM Users WHERE Username = @.Username
";
using (SqlCommand sqlCommand = new SqlCommand(SqlDeleteString, sqlConnection))
{
sqlCommand.Parameters.Add("@.Username", SqlDbType.VarChar).Value = userName;
userId = (int)sqlCommand.ExecuteScalar();
}
}
catch (Exception ee)
{
}
}
return userId;
}
I generally use it like;
using (SqlConnection sqlConnection = newSqlConnection(ConfigurationManager.ConnectionStrings["knovoloCMS"].ConnectionString))
{
if (sqlConnection.state != open)
sqlConnection.open();
......
}
No comments:
Post a Comment