cannot insert data into database

2019-09-02 16:48发布

问题:

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();

回答1:

You don't seem to be actually executing your query. Execute it before you close your connection.

nonquerycommand.ExecuteNonQuery();


回答2:

Two things jump out immediately here.

  1. 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.

  2. You need to call ExecuteNonQuery() on the nonqueryCommand instance.



回答3:

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();


回答4:

Chris Farmer has the money.

Add...

nonqueryCommand.ExecuteNonQuery();


回答5:

you must assign connection to command before executing query for that add following line before thisConnection.Open();

nonqueryCommand.Connection=thisConnection;


回答6:

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.