C# ต้องการ ตรวจสอบ ค่าซ้ำก่อน insert ข้อมูล ลงดาต้าเบสครับ
Code (C#)
public static System.Data.DataTable GetTableForm(string _SQL, string strConn)
{
System.Data.DataSet ds = new System.Data.DataSet();
System.Data.SqlClient.SqlConnection conn3 = new System.Data.SqlClient.SqlConnection(strConn);
conn3.Open();
System.Data.SqlClient.SqlDataAdapter adapter3 = new System.Data.SqlClient.SqlDataAdapter(_SQL, conn3);
adapter3.Fill(ds);
return ds.Tables[0];
}
private void SaveDatabase()
{
string SQL = "";
//เช็คก่อนว่ามีข้อมูลนี้หรือไม่
if (GetTableForm("select * from table where ID = " + "11", "ConnString").Rows.Count > 0)
{
SQL = "Update .... Where ID = " + "11"; //ถ้ามี SQL จะเป็น Update
}
else
{
SQL = "Insert into ...."; //ถ้าไม่มี SQL จะเป็น Insert
}
//เอา SQL ไปใช้งาน
System.Data.DataTable dt = GetTableForm(SQL, "ConnString");
//Save นี้จะได้ทั้ง Update/Insert
}
Date :
2015-02-28 15:08:10
By :
lamaka.tor
Code (C#)
int intNumRows;
strSQL = "SELECT COUNT(*) FROM customer WHERE CustomerID = '"+ this.txtCustomerID.Text +"' ";
objCmd = new MySqlCommand(strSQL, objConn);
intNumRows = Convert.ToInt32(objCmd.ExecuteScalar());
if(intNumRows > 0)
{
this.pnlAdd.Visible = false;
this.lblStatus.Visible = true;
this.lblStatus.Text = "CustomerID already exists.";
}
else
{
strSQL = "INSERT INTO customer (CustomerID,Name,Email,CountryCode,Budget,Used) " +
" VALUES " +
" ('" + this.txtCustomerID.Text + "','" + this.txtName.Text + "','" + this.txtEmail.Text + "', " +
" '" + this.txtCountryCode.Text + "','" + this.txtBudget.Text + "','" + this.txtUsed.Text + "')";
objCmd = new MySqlCommand();
objCmd.Connection = objConn;
objCmd.CommandText = strSQL;
objCmd.CommandType = CommandType.Text;
this.pnlAdd.Visible = false;
try
{
objCmd.ExecuteNonQuery();
this.lblStatus.Text = "Record Inserted";
this.lblStatus.Visible = true;
}
catch (Exception ex)
{
this.lblStatus.Visible = true;
this.lblStatus.Text = "Record can not insert Error ("+ ex.Message +")";
}
}
Date :
2015-02-28 15:09:41
By :
mr.win
Load balance : Server 03