简体   繁体   中英

my insert command not changing the database when using through programming

When I am inserting values with query database is inserting when doing it with coding it won't insert although it show successful. Im using C# 2010 and 2012 Both are not adding My Code

con.Open();
cmd = new SqlCommand("insert into Main_2(Name,NIC,NA_ID,PS_ID) values('" + name + "','" + nic + "',(SELECT NA_ID FROM NationalAssembly WHERE Name='" + na_name + "'),(SELECT PS_ID FROM ProvisionalAssembly Where Name='" + ps_name + "'))", con);
cmd = new SqlCommand("UPDATE ProvisionalAssembly SET Count=+1 WHERE Name='" + ps_name + "'", con);
cmd = new SqlCommand("UPDATE NationalAssembly SET Count=+1 WHERE Name='" + na_name + "'", con);
cmd.ExecuteNonQuery();

con.Close();

SqlCommand is a class , that means it is a reference types .

Everytime you create a new SqlCommand object and you assing it cmd as a reference. That means only your last SqlCommand executes. Your first two SqlCommand doesn't have a reference anymore in memory when you execute with ExecuteNonQuery method.

If you want to execute all these commands, you need to execute separately for each command.

And please use parameterized queries . This kind of string concatenations are open for SQL Injection attacks.

Also use using statement to dispose your database connections.

using(SqlCommand cmd = new SqlCommand(YourInsertStatement))
{
    con.Open();
    cmd.ExecuteNonQuery();

    cmd.CommandText = YourFirstUpdateStatement;
    cmd.ExecuteNonQuery();

    cmd.CommandText = YourSecondUpdateStatement;
    cmd.ExecuteNonQuery();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM