Ali Shan
Ali Shan

Reputation: 527

Visual Studio stops debugging when SqlCommand.ExecuteScalar() is executed

I have this code in my application

SqlConnection sqlConnection1 = new SqlConnection(connectionString);

SqlCommand cmd = new SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;

sqlConnection1.Open();

cmd.CommandText = "SELECT S2 FROM CDUSR WHERE N100 = " + N100.ToString()  ;

var HashStr = cmd.ExecuteScalar();
sqlConnection1.Close();

When I reach at the line

var HashStr = cmd.ExecuteScalar();

Visual Studio 2015 stops debugging my application without any error.

connectionString contains a valid connection string (I have tested)

This query SELECT S2 FROM CDUSR WHERE N100 = 6369 executes successfully in SSMS.

I want to know what the problem is. S2 contains the following string:

a4sd4545ag5645sdfa55sdf45fv5er5cfvg5s45

Upvotes: 0

Views: 281

Answers (2)

PrfctByDsgn
PrfctByDsgn

Reputation: 1050

I guess Visual Studio stops debugging because your code throws an exception (your SqlCommand is not associated with the SqlConnection you use) ... maybe you have "Common Language Runtime Exceptions" disabled in your "Exception Settings" so you don't actually see the exception being thrown ...

Upvotes: 1

pijemcolu
pijemcolu

Reputation: 2605

Are you using the correct constructor for the SqlCommand? It seems to me that you are atleast missing:

cmd.Connection = sqlConnection1

You might as well do that in the constructor when you create the command:

SqlCommand cmd = new SqlCommand("SELECT S2 FROM CDUSR WHERE N100 = " + N100.ToString()), sqlConnection1)

a using block would be nice as well:

using(SqlCommand cmd = new SqlCommand(blah blah)) { cmd.ExecuteScalar; }

Upvotes: 2

Related Questions