我有一个表。我想更新表。实际上我有一个gridview从SQL表中检索值。当页面加载然后gridview加载值。我希望当我在gridview中插入新值然后在SQL表中现有值更新,并且使用SINGLE查询在同一个表中插入新值。我可以这样做吗?告诉我在C#,ASP.NET中工作的SQL查询。我要求UPDATE现有记录并插入新记录在同一个表中同时使用一个查询。感谢
public void insert(object sender, EventArgs e)
{
string user = Session["name"].ToString();
SqlConnection cnn = new SqlConnection("Data Source=HAMEED_KHAN\\SQLEXPRESS;Initial Catalog=db_compiler;Integrated Security=True");
SqlCommand cmd3 = new SqlCommand("SELECT User_ID from tbl_user WHERE User_Name='" + user + "'", cnn);
cnn.Open();
string id = cmd3.ExecuteScalar().ToString();
int ID = Int32.Parse(id);
Session["ID"] = ID;
string d = Session["value"].ToString();
SqlCommand cmd2 = new SqlCommand("SELECT Database_id FROM Create_db WHERE Database_Name='" + d + "'", cnn);
Response.Write("<script>Var Z=Prompt('Enter Table Name');</script>");
string dbid = cmd2.ExecuteScalar().ToString();
cnn.Close();
int D_ID = Int32.Parse(dbid);
string str = "";
string type = "";
for (int i = 0; i < GridView2.Rows.Count; i++)
{
str = GridView2.Rows[i].Cells[1].Text.ToString();
type = GridView2.Rows[i].Cells[2].Text.ToString();
string Name = GridView2.Rows[i].Cells[1].Text.ToString();
string Type = GridView2.Rows[i].Cells[2].Text.ToString();
string size = GridView2.Rows[i].Cells[3].Text.ToString();
CheckBox allow = GridView2.Rows[i].Cells[4].Controls[0] as CheckBox;
CheckBox primary = GridView2.Rows[i].Cells[5].Controls[0] as CheckBox;
string UserID = Session["ID"].ToString();
int UID = Int32.Parse(UserID);
string date = DateTime.Now.ToString();
string A = (allow.Checked == true ? "NULL" : "NOT NULL");
string P = (primary.Checked == true ? "PRIMARY KEY" : "");
string Table = Session["TBL_NAME"].ToString();
string queryy ="USE db_compiler UPDATE tbl_field SET Column_Name='" + Name + "', Data_Type='" + Type + "',Size='" + size + "',Database_id='" + D_ID + "',Allow_Null_='" + (allow.Checked == true ? "true" : "false") + "',Primary_Key_='" + (primary.Checked == true ? "true" : "false") + "',User_id='" + UID + "',Date='" + date + "' WHERE Table_Name='" + Table + "' IF @@ROWCOUNT=0 insert into tbl_field (Table_Name,Column_Name,Data_Type,Size,Database_id,Allow_Null_,Primary_Key_,User_id,Date) VALUES('" + Table + "','" + Name + "','" + Type + "','" + size + "','" + D_ID + "','" + (allow.Checked == true ? "true" : "false") + "','" + (primary.Checked == true ? "true" : "false") + "','" + UID + "','" + date + "')";
SqlCommand cmd = new SqlCommand(queryy, cnn);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
}
}
以下是我的网格视图图片image表格名称为employee
我首先在网格视图中有3行Name
,id
,&#39;地址&#39;当我插入新行ph
并点击update table
时,我会使用ph
Db-image更新所有行