Reputation: 3047
I just want what my title says.I have already read all the previous similar posts but i couldn't find a solution .Could you please take a watch into my code? EDIT:I don't get any exception.I just don't see the new data in the database EDIT2:The first 4 answers don't solve my problem because i edited the code and added the executenonquery command.
int admin = 23;
SqlConnection thisConnection = new SqlConnection(
ConfigurationManager.ConnectionStrings[
"Data Source=...;Persist Security Info=True;User ID=myusername;Password=mypassword"]
.ConnectionString);
SqlCommand nonqueryCommand = thisConnection.CreateCommand();
thisConnection.Open();
nonqueryCommand.CommandText = "INSERT INTO Account (Username,Password,AdministratorId) VALUES (@username,@password,@admin)";
nonqueryCommand.Parameters.Add("@username", SqlDbType.VarChar, 20);
nonqueryCommand.Parameters["@username"].Value = UsernameTextbox.Text.ToString();
nonqueryCommand.Parameters.Add("@password", SqlDbType.VarChar, 15);
nonqueryCommand.Parameters["@password"].Value = PasswordTextbox.Text.ToString();
nonqueryCommand.Parameters.Add("@admin", SqlDbType.Int);
nonqueryCommand.Parameters["@admin"].Value = admin;
EDIT:nonquerycommand.ExecuteNonQuery();
thisConnection.Close();
Upvotes: 0
Views: 679
Reputation: 19
You have to execute the query and close your connection after this as shown below
nonquerycommand.ExecuteNonQuery();
or if you want to check if query is executed or not do this
if(nonquerycommand.ExecuteNonQuery()>0){ //some message or function }
the returned value are the number of rows affected by the statement.
Upvotes: 0
Reputation: 7403
you must assign connection to command before executing query for that add following line before thisConnection.Open();
nonqueryCommand.Connection=thisConnection;
Upvotes: 0
Reputation: 53699
Two things jump out immediately here.
When you retrieve the connection string from ConfigurationManager.ConnectionStrings
you should be passing the name of the connection string in the config file and not the connection string it self. I suspect you might not even be getting a valid connection string.
You need to call ExecuteNonQuery()
on the nonqueryCommand
instance.
Upvotes: 3
Reputation: 6931
Chris Farmer has the money.
Add...
nonqueryCommand.ExecuteNonQuery();
Upvotes: 2
Reputation: 13655
Instead of
nonqueryCommand.Parameters.Add("@username", SqlDbType.VarChar,20);
nonqueryCommand.Parameters["@username"].Value = UsernameTextbox.Text.ToString();
Use
nonqueryCommand.Parameters.AddWithValue("@username", UsernameTextbox.Text.ToString());
And execute your query:
nonquerycommand.ExecuteNonQuery();
Upvotes: 2
Reputation: 25386
You don't seem to be actually executing your query. Execute it before you close your connection.
nonquerycommand.ExecuteNonQuery();
Upvotes: 6