i'm working on restaurants programming with c#
working on the daily quantity of the material
i do count of the total that they make on the day then count how many they used and how many remaining on that day
my code is
public void ExecuteQuery(string query)
{
foreach (Control txt in this.Controls)
{
if (txt.GetType() == typeof(TextBox))
if (string.IsNullOrEmpty(txt.Text))
txt.Text = "0";
}
SqlCommand com = new SqlCommand(query, connection);
com.Parameters.Add("#shish_add", SqlDbType.Int).Value = shish_add.Text;
com.Parameters.Add("#bani_add", SqlDbType.Int).Value = bani_add.Text;
com.Parameters.Add("#zingr_add", SqlDbType.Int).Value = zingr_add.Text;
com.Parameters.Add("#tabona_add", SqlDbType.Int).Value = tabona_add.Text;
com.Parameters.Add("#fahita_chkn_add", SqlDbType.Int).Value = fahita_chkn_add.Text;
com.Parameters.Add("#borger_add", SqlDbType.Int).Value = borger_add.Text;
com.Parameters.Add("#kabab_add", SqlDbType.Int).Value = kabab_add.Text;
com.Parameters.Add("#shgef_add", SqlDbType.Int).Value = shgef_add.Text;
com.Parameters.Add("#faheta_met_add", SqlDbType.Int).Value = faheta_met_add.Text;
com.Parameters.Add("#kabda_add", SqlDbType.Int).Value = kabda_add.Text;
com.Parameters.Add("#shawo_met_add", SqlDbType.Int).Value = shawo_met_add.Text;
com.Parameters.Add("#shawo_chkn_add", SqlDbType.Int).Value = shawo_chkn_add.Text;
com.Parameters.Add("#chkn_mash_add", SqlDbType.Int).Value = chkn_mash_add.Text;
com.Parameters.Add("#chkn_red_add", SqlDbType.Int).Value = chkn_red_add.Text;
com.Parameters.Add("#patata_add", SqlDbType.Int).Value = patata_add.Text;
com.Parameters.Add("#shish_take", SqlDbType.Int).Value = shish_take.Text;
com.Parameters.Add("#bani_take", SqlDbType.Int).Value = bani_take.Text;
com.Parameters.Add("#zingr_take", SqlDbType.Int).Value = zingr_take.Text;
com.Parameters.Add("#tabona_take", SqlDbType.Int).Value = tabona_take.Text;
com.Parameters.Add("#fahita_chkn_take", SqlDbType.Int).Value = fahita_chkn_take.Text;
com.Parameters.Add("#borger_take", SqlDbType.Int).Value = borger_take.Text;
com.Parameters.Add("#kabab_take", SqlDbType.Int).Value = kabab_take.Text;
com.Parameters.Add("#shgef_take", SqlDbType.Int).Value = shgef_take.Text;
com.Parameters.Add("#faheta_met_take", SqlDbType.Int).Value = faheta_met_take.Text;
com.Parameters.Add("#kabda_take", SqlDbType.Int).Value = kabda_take.Text;
com.Parameters.Add("#shawo_met_take", SqlDbType.Int).Value = shawo_met_take.Text;
com.Parameters.Add("#shawo_chkn_take", SqlDbType.Int).Value = shawo_chkn_take.Text;
com.Parameters.Add("#chkn_mash_take", SqlDbType.Int).Value = chkn_mash_take.Text;
com.Parameters.Add("#chkn_red_take", SqlDbType.Int).Value = chkn_red_take.Text;
com.Parameters.Add("#patata_take", SqlDbType.Int).Value = patata_take.Text;
com.Parameters.Add("#shish_rom", SqlDbType.Int).Value = shish_rom.Text;
com.Parameters.Add("#bani_rom", SqlDbType.Int).Value = bani_rom.Text;
com.Parameters.Add("#zingr_rom", SqlDbType.Int).Value = zingr_rom.Text;
com.Parameters.Add("#tabona_rom", SqlDbType.Int).Value = tabona_rom.Text;
com.Parameters.Add("#fahita_chkn_rom", SqlDbType.Int).Value = fahita_chkn_rom.Text;
com.Parameters.Add("#borger_rom", SqlDbType.Int).Value = borger_rom.Text;
com.Parameters.Add("#kabab_rom", SqlDbType.Int).Value = kabab_rom.Text;
com.Parameters.Add("#shgef_rom", SqlDbType.Int).Value = shgef_rom.Text;
com.Parameters.Add("#faheta_met_rom", SqlDbType.Int).Value = faheta_met_rom.Text;
com.Parameters.Add("#kabda_rom", SqlDbType.Int).Value = kabda_rom.Text;
com.Parameters.Add("#shawo_met_rom", SqlDbType.Int).Value = shawo_met_rom.Text;
com.Parameters.Add("#shawo_chkn_rom", SqlDbType.Int).Value = shawo_chkn_rom.Text;
com.Parameters.Add("#chkn_mash_rom", SqlDbType.Int).Value = chkn_mash_rom.Text;
com.Parameters.Add("#chkn_red_rom", SqlDbType.Int).Value = chkn_red_rom.Text;
com.Parameters.Add("#patata_rom", SqlDbType.Int).Value = patata_rom.Text;
com.Parameters.Add("#dates", SqlDbType.DateTime).Value = dates.Value.Date;
if (connection.State == ConnectionState.Closed)
connection.Open();
com.ExecuteNonQuery();
connection.Close();
foreach (Control txt in this.Controls)
{
if (txt.GetType() == typeof(TextBox))
if (txt.Text == "0")
txt.Text = "";
}
MessageBox.Show("تمت عملية الاضافة بنجاح", "ملاحظة", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
}
public void doqury(string strn)
{
string sqlQuery = strn;
ExecuteQuery(sqlQuery);
}
private void button1_Click(object sender, EventArgs e)
{
// check for first time entry
SqlCommand cmd = new SqlCommand("select * from megana_cooking ", connection);
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
//mean there values on database
//now need to check is this a new day or not
SqlCommand cmd1 = new SqlCommand("select * from megana_cooking where dates = #dates", connection);
connection.Open();
SqlDataReader reader1 = cmd.ExecuteReader();
if (reader1.HasRows)
{
//no this is the take valus statment
reader.Close();
doqury("UPDATE megana_cooking SET shish_rom =shish_add - #shish_take ,bani_rom =bani_add - #bani_take ,zingr_rom =zingr_add - #zingr_take ,tabona_rom =tabona_add - #tabona_take ,fahita_chkn_rom =fahita_chkn_add - #fahita_chkn_take ,borger_rom =borger_add - #borger_take ,kabab_rom =kabab_add - #kabab_take ,shgef_rom =shgef_add - #shgef_take ,faheta_met_rom =faheta_met_add - #faheta_met_take ,kabda_rom =kabda_add - #kabda_take ,shawo_met_rom =shawo_met_add - #shawo_met_take ,shawo_chkn_rom =shawo_chkn_add - #shawo_chkn_take ,chkn_mash_rom =chkn_mash_add - #chkn_mash_take ,chkn_red_rom =chkn_red_add - #chkn_red_take ,patata_rom =patata_add - #patata_take ,patata_take =#patata_take,chkn_red_take =#chkn_red_take,chkn_mash_take =#chkn_mash_take,shawo_chkn_take =#shawo_chkn_take,shawo_met_take =#shawo_met_take,kabda_take =#kabda_take,faheta_met_take =#faheta_met_take,shgef_take =#shgef_take,kabab_take =#kabab_take,borger_take =#borger_take,fahita_chkn_take =#fahita_chkn_take,tabona_take =#tabona_take,zingr_take =#zingr_take,bani_take =#bani_take,shish_take =#shish_take ,dates =#dates where dates = #dates ");
}
else
{
// yes new day new values and add value to the remain values from last entry
DialogResult result = MessageBox.Show("سيتم ادخال بيانات ليوم جديد " + Environment.NewLine + " سيقوم بأدخال البيانات دون احتساب عملية السحب", "تأكيد", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1,
MessageBoxOptions.RightAlign);
doqury("INSERT INTO megana_cooking ( shish_add ,bani_add ,zingr_add ,tabona_add ,fahita_chkn_add ,borger_add ,kabab_add ,shgef_add ,faheta_met_add ,kabda_add ,shawo_met_add ,shawo_chkn_add ,chkn_mash_add ,chkn_red_add ,patata_add ,dates ) VALUES ( #shish_add ,#bani_add ,#zingr_add ,#tabona_add ,#fahita_chkn_add ,#borger_add ,#kabab_add ,#shgef_add ,#faheta_met_add ,#kabda_add ,#shawo_met_add ,#shawo_chkn_add ,#chkn_mash_add ,#chkn_red_add ,#patata_add ,#dates )");
//insert new quentity done now need to update the remain value
//new quentity + last remain
here need to find the last date that it have value then update and add the new quantity to it
}
}
else
{
//this is first entry
reader.Close();
DialogResult result = MessageBox.Show("سيتم ادخال البيانات الى المنظومة لاول مره " + Environment.NewLine + " سيقوم بأدخال البيانات دون احتساب عملية السحب", "تأكيد", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1,
MessageBoxOptions.RightAlign);
doqury("INSERT INTO megana_cooking ( shish_add ,bani_add ,zingr_add ,tabona_add ,fahita_chkn_add ,borger_add ,kabab_add ,shgef_add ,faheta_met_add ,kabda_add ,shawo_met_add ,shawo_chkn_add ,chkn_mash_add ,chkn_red_add ,patata_add ,shish_rom ,bani_rom ,zingr_rom ,tabona_rom ,fahita_chkn_rom ,borger_rom ,kabab_rom ,shgef_rom ,faheta_met_rom ,kabda_rom ,shawo_met_rom ,shawo_chkn_rom ,chkn_mash_rom ,chkn_red_rom ,patata_rom ,dates ) VALUES ( #shish_add ,#bani_add ,#zingr_add ,#tabona_add ,#fahita_chkn_add ,#borger_add ,#kabab_add ,#shgef_add ,#faheta_met_add ,#kabda_add ,#shawo_met_add ,#shawo_chkn_add ,#chkn_mash_add ,#chkn_red_add ,#patata_add ,#shish_add ,#bani_add ,#zingr_add ,#tabona_add ,#fahita_chkn_add ,#borger_add ,#kabab_add ,#shgef_add ,#faheta_met_add ,#kabda_add ,#shawo_met_add ,#shawo_chkn_add ,#chkn_mash_add ,#chkn_red_add ,#patata_add ,#dates )");
}
connection.Close();
}
the question is
i need to find the last date that it have value then update and add the new quantity to it i did mention it in my code
i know i can because when i tried this code on new query on sql management studio it work
SELECT
*
FROM
megana_cooking
ORDER BY
dates
update megana_cooking set shish_rom = shish_rom + '5'
can i make the sql command shorter than this by using sql programmability or server side because i have more than 15 type of the material food
i have weak knowledge about sql
thank you in advance
Related
the image above shows the output inside mysql Tables.
my problem is it cannot get the value of last_inserted_id value in ORDERTABLE, as it is the reference value in ItemTable itemid.
this is my code in SAVEORDER and SAVEITEM
the description =is where I split the Data into a foreach and save it in item table.
each split should save each data with corresponding orderid, I tried last_inserted_id and not MaxID as i want it to be done by 1-3 user simultaneously without having problem in data integrity.
private void SaveOrder()
{
try
{
foreach (DataGridViewRow row in DGSingleOrders.Rows)
{
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.CommandText = "INSERT INTO single_order (customerid, category, type, description, code, color, price, status, transaction, attendee) VALUES (#customerid, #category, #type, #description, #code, #color, #price, #status, #transaction, #attendee)";
cmd.CommandType = CommandType.Text;
cmd.Connection = db.con;
db.con.Open();
cmd.Parameters.Add("#customerid", MySqlDbType.VarChar).Value = OrderID;
cmd.Parameters.Add("#category", MySqlDbType.VarChar).Value = row.Cells[0].Value.ToString();
cmd.Parameters.Add("#type", MySqlDbType.VarChar).Value = row.Cells[1].Value.ToString();
cmd.Parameters.Add("#description", MySqlDbType.VarChar).Value = row.Cells[2].Value.ToString();
cmd.Parameters.Add("#code", MySqlDbType.VarChar).Value = row.Cells[3].Value.ToString();
cmd.Parameters.Add("#color", MySqlDbType.VarChar).Value = row.Cells[4].Value.ToString();
cmd.Parameters.Add("#price", MySqlDbType.VarChar).Value = row.Cells[5].Value.ToString();
cmd.Parameters.Add("#status", MySqlDbType.VarChar).Value = SaveAs;
cmd.Parameters.Add("#transaction", MySqlDbType.VarChar).Value = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss tt");
cmd.Parameters.Add("#attendee", MySqlDbType.VarChar).Value = attendee;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
db.con.Close();
}
//Check this first
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.CommandText = "SELECT LAST_INSERT_ID()";
cmd.Connection = db.con;
db.con.Open();
using (MySqlDataReader reader = cmd.ExecuteReader())
{
long id;
while (reader.Read())
{
id = reader.GetInt64(0);
ItemID = id.ToString();
}
db.con.Close();
}
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message,"ORDER");
db.con.Close();
return;
}
}
private void SaveItem()
{
//Getting Each Data
foreach (DataGridViewRow row in DGSingleOrders.Rows)
{
string item = row.Cells[1].Value.ToString();
string type = row.Cells[0].Value.ToString();
string str = row.Cells[2].Value.ToString();
string code = row.Cells[3].Value.ToString();
string color = row.Cells[4].Value.ToString();
List<string> descr = str.Split('+').ToList<string>();
//Splitting Description
//Adding Split to a DataTable
foreach (var l in descr)
{
OrderRow = l;
try
{
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.CommandText = "INSERT INTO single_item (orderid, type, item, brand, code, color, eventdate, orderstatus, itemstatus, orderchecker, attendee)VALUES(#orderid, #type, #item, #brand, #code, #color, #eventdate, #orderstatus, #itemstatus, #orderchecker, #attendee)";
cmd.CommandType = CommandType.Text;
cmd.Connection = db.con;
cmd.Parameters.Add("#orderid", MySqlDbType.VarChar).Value = ItemID;
cmd.Parameters.Add("#type", MySqlDbType.VarChar).Value = type;
cmd.Parameters.Add("#item", MySqlDbType.VarChar).Value = OrderRow;
cmd.Parameters.Add("#brand", MySqlDbType.VarChar).Value = "-";
cmd.Parameters.Add("#code", MySqlDbType.VarChar).Value = code;
cmd.Parameters.Add("#color", MySqlDbType.VarChar).Value = color;
cmd.Parameters.Add("#eventdate", MySqlDbType.VarChar).Value = eventDay;
cmd.Parameters.Add("#orderstatus", MySqlDbType.VarChar).Value = SaveAs;
cmd.Parameters.Add("#itemstatus", MySqlDbType.VarChar).Value = "Good";
cmd.Parameters.Add("#orderchecker", MySqlDbType.VarChar).Value = "Not Updated";
cmd.Parameters.Add("#attendee", MySqlDbType.VarChar).Value = atendee;
db.con.Open();
cmd.ExecuteNonQuery();
db.con.Close();
dtItems.Clear();
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
db.con.Close();
return;
}
SaveItem();
}
}
I added SaveItem(); Method inside SaveOrder(); ForeachLoop so that it can save together with the ORDER table, and can fetch the data of Last_inserted_id but it still get the first ID, I also tried putting it out the foreach loop, but then I can't get the result of the Order ID, and save data differently.
You can use MySqlCommand.LastInsertedId to get the ID of the row that was just inserted, without a separate query. It's also guaranteed to contain the correct value because it comes directly from MySQL's response to the INSERT statement.
long itemId;
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.CommandText = "INSERT INTO single_order (customerid, ...";
// ...
cmd.ExecuteNonQuery();
itemId = cmd.LastInsertedId;
}
// ...
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.CommandText = "INSERT INTO single_item (orderid, ...";
cmd.Parameters.AddWithValue("#orderid", itemID);
// ...
}
So I figure it out.
Instead of using SELECT LAST_INSERT_ID() which has some documentation that it only returns the first ID that has been insert. Bradley Grainger offer to use MySqlCommand.InsertLastId;
I've modified it to this.
cmd.ExecuteNonQuery();
cmd.Parameters.Add(new MySqlParameter("newId", cmd.LastInsertedId));
ItemID = Convert.ToInt32(cmd.Parameters["#newId"].Value);
MessageBox.Show(ItemID.ToString());
```
now it is working. It can fetch the lastInserted iD in each loop, and the beauty of it is it can be threadsafe and can work along with simultaneous insert.
Also this link help me. https://livshitz.wordpress.com/2011/10/28/returning-last-inserted-id-in-c-using-mysql-db-provider/
I have a button click function which runs a stored procedure.
The stored procedure returns data. After execution depend upon the datareader output another command needs to be executed.
using (SqlDataReader oReader = command.ExecuteReader())
{
while (oReader.Read())
{
if (oReader["comments1"].ToString() == "0")
{
MessageBox.Show("CHECK THE COMMENTS AND THE GIVEN VALUE");
;
}
else
{
command.ExecuteNonQuery();
MessageBox.Show("Inserted data");
ClearTextBoxes(this);
button2.Enabled = false;
}
}
}
There is already an open DataReader associated with this Command which
must be closed first
I know that im trying to use same connection for reading and also for writing the data in the table.
Whether there is any other approach to solve the given problem.
Entire Function:
private void button2_Click(object sender, EventArgs e)
{
var connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var command = new SqlCommand(#"[lis1].[_Submit_test]", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Date", SqlDbType.Date).Value = textBox1.Text;
command.Parameters.Add("#Username", SqlDbType.VarChar).Value = textBox11.Text;
command.Parameters.Add("#workflow", SqlDbType.VarChar).Value = comboBox2.Text;
command.Parameters.Add("#program", SqlDbType.VarChar).Value = comboBox1.Text;
command.Parameters.Add("#Full_Denial", SqlDbType.Int).Value = textBox2.Text;
command.Parameters.Add("#Partial_Denial", SqlDbType.Int).Value = textBox3.Text;
command.Parameters.Add("#No_Findings", SqlDbType.Int).Value = textBox4.Text;
command.Parameters.Add("#Rejections", SqlDbType.Int).Value = textBox5.Text;
command.Parameters.Add("#Unfulfilled", SqlDbType.Int).Value = textBox6.Text;
command.Parameters.Add("#TargetPerDay", SqlDbType.Int).Value = textBox7.Text;
command.Parameters.Add("#Audits_Assigned", SqlDbType.Int).Value = textBox10.Text;
command.Parameters.Add("#Total_Audits_Reviewed", SqlDbType.Int).Value = textBox12.Text;
command.Parameters.Add("#Audits_Carry_Forward", SqlDbType.Int).Value = textBox8.Text;
command.Parameters.Add("#Pending_Audits", SqlDbType.Int).Value = textBox9.Text;
command.Parameters.Add("#Comments", SqlDbType.VarChar).Value = comboBox3.Text;
SqlParameter returnParameter = command.Parameters.Add("RetVal", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
using (SqlDataReader oReader = command.ExecuteReader())
{
while (oReader.Read())
{
if (oReader["comments1"].ToString() == "0")
{
MessageBox.Show("CHECK THE COMMENTS AND THE GIVEN VALUE");
}
else
{
command.ExecuteNonQuery();
MessageBox.Show("Inserted data");
ClearTextBoxes(this);
button2.Enabled = false;
}
}
}
}
}
}
I tried to execute same command using command.ExecuteReader() and using command.ExecuteNonQuery() after i removed the command.ExecuteNonQuery(). Everything works as i expected.
using (SqlDataReader oReader = command.ExecuteReader())
{
while (oReader.Read())
{
if (oReader["comments1"].ToString() == "0")
{
MessageBox.Show("CHECK THE COMMENTS AND THE GIVEN VALUE");
;
}
else
{
MessageBox.Show("Inserted");
ClearTextBoxes(this);
button2.Enabled = false;
}
}
I have this procedure :
CREATE PROCEDURE UpdateVolunteers
#Vol_ID INT,
#Vol_Name NVARCHAR(50),
#Vol_Zone NVARCHAR(50),
#vol_street NVARCHAR(50),
#Vol_Sex INT,
#Vol_Date_of_Birth DATE,
#Vol_Home_Phone INT,
#Vol_Work_Phone INT,
#Vol_Mobile1 INT,
#Vol_Mobile2 INT,
#Vol_Email NVARCHAR(50),
#Vol_Job NVARCHAR(50),
#Vol_Affiliation NVARCHAR(50),
#vol_Education INT,
#vol_Education_Place NVARCHAR(50),
#vol_Education_Department NVARCHAR(50),
#vol_Interesting INT,
#Team_ID INT,
#vol_Notes NVARCHAR(50)
AS
IF #team_id = -1
BEGIN
SET #team_id = NULL
END
UPDATE Personal_Info
SET Vol_Name = #Vol_Name,
Vol_Zone = #Vol_Zone,
vol_street = #vol_street,
Vol_Sex = #Vol_Sex,
Vol_Date_of_Birth = #Vol_Date_of_Birth,
Vol_Home_Phone = #Vol_Home_Phone,
Vol_Work_Phone = #Vol_Work_Phone,
Vol_Mobile1 = #Vol_Mobile1,
Vol_Mobile2 = #Vol_Mobile2,
Vol_Email = #Vol_Email,
Vol_Job = #Vol_Job,
Vol_Affiliation = #Vol_Affiliation,
vol_Education = #vol_Education,
vol_Education_Place = #vol_Education_Place,
vol_Education_Department = #vol_Education_Department,
vol_Interesting = #vol_Interesting,
Team_ID = #Team_ID,
vol_Notes = #vol_Notes
WHERE Vol_ID = #Vol_ID
and I called it to C# application by this code:
private static void UpdateVolunteer(string volID, string volName, string volZone,
string volStreet, int volSex, DateTime volBirthday, int volHomePhone,
int volWorkPhone, int volMobile1, int volMobile2, string volEmail,
string volJob, string volAffiliation, int volEducation,
string volEducationPlace, string volEducationDepartment, int volInteresting,
int Team_ID, string volNotes)
{
try
{
SqlCommand com = new SqlCommand("UpdateVolunteers", con);
com.Parameters.Add("#Vol_ID", SqlDbType.Int).Value = volID;
com.Parameters.Add("#Vol_Name", SqlDbType.NVarChar, 50).Value = volName;
com.Parameters.Add("#Vol_Zone", SqlDbType.NVarChar, 50).Value = volZone;
com.Parameters.Add("#vol_street", SqlDbType.NVarChar, 50).Value = volStreet;
com.Parameters.Add("#Vol_Sex", SqlDbType.Int).Value = volSex;
com.Parameters.Add("#Vol_Date_of_Birth", SqlDbType.DateTime).Value = volBirthday;
com.Parameters.Add("#Vol_Home_Phone", SqlDbType.Int).Value = volHomePhone;
com.Parameters.Add("#Vol_Work_Phone", SqlDbType.Int).Value = volWorkPhone;
com.Parameters.Add("#Vol_Mobile1", SqlDbType.Int).Value = volMobile1;
com.Parameters.Add("#Vol_Mobile2", SqlDbType.Int).Value = volMobile2;
com.Parameters.Add("#Vol_Email", SqlDbType.NVarChar, 50).Value = volEmail;
com.Parameters.Add("#Vol_Job", SqlDbType.NVarChar, 50).Value = volJob;
com.Parameters.Add("#Vol_Affiliation", SqlDbType.NVarChar, 50).Value = volAffiliation;
com.Parameters.Add("#vol_Education", SqlDbType.Int).Value = volEducation;
com.Parameters.Add("#vol_Education_Place", SqlDbType.NVarChar, 50).Value = volEducationPlace;
com.Parameters.Add("#vol_Education_Department", SqlDbType.NVarChar, 50).Value = volEducationDepartment;
com.Parameters.Add("#vol_Interesting", SqlDbType.Int).Value = volInteresting;
com.Parameters.Add("#vol_Notes", SqlDbType.NVarChar, 50).Value = volNotes;
com.Parameters.Add("#Team_ID", SqlDbType.Int);
com.Parameters["#Team_ID"].Value = Team_ID;
com.CommandType = System.Data.CommandType.StoredProcedure;
if (con.State != ConnectionState.Open)
con.Open();
com.ExecuteNonQuery();
con.Close();
}
catch (SqlException sqlEx)
{
if (con.State == ConnectionState.Open)
con.Close();
throw sqlEx;
}
}
And this Function in C#: Called in Button_Click event
public void showVolunteers(int x)
{
SqlCommand com = new SqlCommand("SELECT [Vol_ID]
,[Vol_Name]
,[Vol_Zone]
,[vol_street]
,[Vol_Sex]
,[vol_Age]
,[Vol_Date_of_Birth]
,[Vol_Home_Phone]
,[Vol_Work_Phone]
,[Vol_Mobile1]
,[Vol_Mobile2]
,[Vol_Email]
,[Vol_Job]
,[Vol_Affiliation]
,[vol_Education]
,[vol_Education_Place]
,[vol_Education_Department]
,[vol_Interesting]
,[vol_Hours]
,[vol_Notes]
,[Team_ID]
FROM [VolunteersAffairs].[dbo].[Personal_Info]", con);
SqlDataAdapter da = new SqlDataAdapter();
DataSet dats = new DataSet();
da.SelectCommand = com;
da.Fill(dats, "Personal_Info");
dataGridViewX1.DataSource = dats.Tables["Personal_Info"];
dataGridViewX1.Columns[2].DefaultCellStyle.NullValue = "Nothing";
updateComboBox.SelectedIndex = updateComboBox.Items.Count - 1;
if (x != -1)
{
dataGridViewX1.Rows[x].Selected = true;
dataGridViewX1.CurrentCell = dataGridViewX1[0, x];
}
labelItem1.Text = "Number of Volunteers = " + dataGridViewX1.Rows.Count;
int X = 0, Y = 0;
foreach (DataGridViewRow n in dataGridViewX1.Rows)
{
if (n.Cells[5].Value.ToString() == "Male")
X++;
else
Y++;
}
labelItem2.Text = " | Number of Males = " + X + " |Number of Female = " + Y;
//When I put the following as a comment the update is so fast, else very slowly.
//This operation takes the birthday of volunteers and calculate the age for every one.
//And calculate the age in runTime and the value of the column in database is null and always be.
#region the problem has been detected here
DateTime brithday;
for (int i = 0; i < dataGridViewX1.Rows.Count; i++)
{
brithday = (DateTime)dataGridViewX1[6, i].Value;
TimeSpan age = DateTime.Today - brithday;
dataGridViewX1[7, i].Value = age.Days / 365;
}
#endregion
}
The problem is that the code takes so long (about 1 min) to execute when I update the table via the form of C#, but it so fast when I update it via code in sql query. Is the problem in the code of C# or in the called procedure?
Tell me what is the solution for this problem. Please!!
You have this in a try catch block. Try catch blocks are expensive, and you probably don't need one to perform an sql query.
try catch performance
Instead of a try block, use a using block, which will instruct the garbage collector not to dispose the connection or command and the connection will be closed at the end of the using block as well.
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand("UpdateVolunteers", connection))
{
command.Parameters.AddWithValue("#Vol_ID", volID);
// other paramters...
connection.Open();
command.ExecuteNonQuery();
}
}
Error Text : Incorrect syntax near '='.
What is the error in my Code?
How I Can Select It right
this code to sure if this found or not
its All my Code Plz Check It
its to check my value and update some it
or insert
ssssssssssssssssssssssssssssssssssssssssssssssssssssssss
//Test For Insert Duplicate Row
int tst = 0;
SqlCommand cmd = new SqlCommand("Select Count(*) From Product Where ProdCode=#CodeVar And ProdName= #NameVar And BuyPrice=#PriceVar",conn);
cmd.Parameters.Add("#CodeVar", SqlDbType.Int).Value = Convert.ToDouble(dataGridView1.Rows[x].Cells[1].Value);
cmd.Parameters.Add("#NameVar", SqlDbType.NVarChar).Value = dataGridView1.Rows[x].Cells[2].Value;
cmd.Parameters.Add("#PriceVar", SqlDbType.Money).Value = Convert.ToDouble(dataGridView1.Rows[x].Cells[4].Value);
cmd.CommandType = CommandType.Text;
conn.Open();
SqlDataReader reader= cmd.ExecuteReader();
if(reader.Read())
{
if (Convert.ToInt16(reader[0]) > 0)
{
tst = 1;
}
}
reader.Close();
conn.Close();
// Test For Same Row But Anthor Code
cmd.CommandText = "Select Count(*) From Product Where ProdName=#PName And BuyPrice=#BPrice And Not ProdCode = #Pcode And ProdCode BETWEEN #SCode And #SCode+2000";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#PName",SqlDbType.NVarChar).Value = dataGridView1.Rows[x].Cells[2].Value ;
cmd.Parameters.Add("#BPrice", SqlDbType.Money).Value = Convert.ToDouble(dataGridView1.Rows[x].Cells[5].Value);
cmd.Parameters.Add("#Pcode",SqlDbType.Int).Value = Convert.ToInt32(dataGridView1.Rows[x].Cells[1].Value);
cmd.Parameters.Add("#SCode", SqlDbType.Decimal).Value = Convert.ToDecimal(label10.Text);
cmd.CommandType = CommandType.Text;
conn.Open();
reader = cmd.ExecuteReader();
if(reader.Read())
{
if(Convert.ToInt16(reader[0])>0)
{
tst = 2;
}
}
reader.Close();
conn.Close();
cmd.CommandText = "Select Count(*) From Product Where ProdCode = #CodeVar1 ";
cmd.Parameters.Add("#CodeVar1", SqlDbType.Int).Value = Convert.ToInt32(dataGridView1.Rows[x].Cells[1].Value);
cmd.CommandType = CommandType.Text;
conn.Open();
reader= cmd.ExecuteReader();
if (reader.Read())
{
if (Convert.ToInt16(reader[0]) > 0 && tst == 0)
{
MessageBox.Show("الأكواد باللون الأحمر خاصة احد الأصناف ..!");
dataGridView1.Rows[x].Cells[1].Style = redcell;
return;
}
}
reader.Close();
conn.Close();
You should try to replace ProdCode Not = #Pcode with ProdCode != #Pcode or ProdCode <> #Pcode or Not ProdCode = #Pcode.
All should be valid in TSQL.
change
and ProdCode Not = #Pcode
to
and not ProdCode = #Pcode
You need to replace the ProdCode Not = #Pcode in your sql command with ProdCode <> #Pcode
I am making a booking system.
I can't figure out the validation algorithm for a series of data before it insert to DB.
The primary key will be the booking ID which is automatic generate by the system.
I need to validate the bdate, btime and sname. (bdate=booking time, btime=booking time, and sname=staff name)
In case of the bdate, btime and sname is same as what the client input. the system will alert its duplicate as the staff already have booking on the same date and time.
Please find my insert query at below and appreciated you can point me to the right way.
private void btn_save_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
//query for duplicate
cmd.CommandText = "select count(*) from Booking where sname = #newName and bdate = #newDate and btime = #newTime";
// cmd.Parameters.Add("#newName", OleDbType.VarChar).Value = txt_cname.Text;
//cmd.Parameters.Add("#newDate", OleDbType.DBDate).Value = dtp_bdate.Value.Date;
// cmd.Parameters.Add("#newTime", OleDbType.VarChar).Value = dtp_btime.Value.ToString("hh:mm tt");
cmd.CommandText = "insert into Booking(cname, bdate, btime, ccontact, sname) Values('" + txt_cname.Text + "','" + dtp_bdate.Value.Date + "','" + dtp_btime.Value.ToString("hh:mm tt") + "','" + txt_ccontact.Text + "','" + txt_sname.Text + "')";
cmd.Connection = myCon;
myCon.Open();
int recordCount = Convert.ToInt32(cmd.ExecuteScalar());
myCon.Close();
if (recordCount>0)
{
// handle duplicates
MessageBox.Show("Duplicated", "My Application",
MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
// cmd.Connection = myCon;
//myCon.Open();
//cmd.ExecuteNonQuery();
//myCon.Close();
//MessageBox.Show(dtp_bdate.Value.ToString());
//MessageBox.Show("Booking completed", "My Application",
// MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
private bool RecordExists(string name, DateTime date, string time)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
//query for duplicate
cmd.CommandText = "select count(*) from Booking where sname = #newName and bdate = #newDate and btime = #newTime";
cmd.Parameters.Add("#newName", OleDbType.VarChar).Value = txt_cname.Text;
cmd.Parameters.Add("#newDate", OleDbType.DBDate).Value = dtp_bdate.Value.Date;
cmd.Parameters.Add("#newTime", OleDbType.VarChar).Value = dtp_btime.Value.ToString("hh:mm tt");
myCon.Open();
int recordCount = Convert.ToInt32(cmd.ExecuteScalar());
myCon.Close();
return recordCount > 0;
}
private void btn_save_Click(object sender, EventArgs e)
{
if (RecordExists(txt_cname.Text, dtp_bdate.Value.Date, dtp_btime.Value.ToString("hh:mm tt"))
{
MessageBox.Show("Duplicated", "My Application", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
return;
}
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Booking(cname, bdate, btime, ccontact, sname) Values(#newName, #newDate, #newTime, #newContact, #newSName)";
cmd.Parameters.Add("#newName", OleDbType.VarChar).Value = txt_cname.Text;
cmd.Parameters.Add("#newDate", OleDbType.DBDate).Value = dtp_bdate.Value.Date;
cmd.Parameters.Add("#newTime", OleDbType.VarChar).Value = dtp_btime.Value.ToString("hh:mm tt");
cmd.Parameters.Add("#newContact", OleDbType.VarChar).Value = txt_ccontact.Text;
cmd.Parameters.Add("#newSName", OleDbType.VarChar).Value = txt_sname.Text;
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
myCon.Close();
MessageBox.Show(dtp_bdate.Value.ToString());
MessageBox.Show("Booking completed", "My Application", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
you'll need to check if the booking exists before performing your insert, so you need to add an additional step:
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select count(*) from booking where cname = #newName and bdate = #newDate and ctime = #newTime";
cmd.Parameters.Add("#newName", OleDbType.VarChar).Value = txt_cname.Text;
cmd.Parameters.Add("#newDate", OleDbType.DBDate).Value = dtp_bdate.Value.Date;
cmd.Parameters.Add("#newTime", OleDbType.VarChar).Value = dtp_btime.Value.ToString("hh:mm tt");
cmd.Connection = myCon;
myCon.Open();
int recordCount = Convert.ToInt32(cmd.ExecuteScalar());
myCon.Close();
if (recordCount>0)
{
// handle duplicates
}
when you execute this, it will either return the number of matching rows, if this is 1 or more, then you should then invoke your duplicate logic.
edited to correct code
To check if there's existing field you can make a Select and then compare:
bool InfoRepeated()
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = string.Format("SELECT cname FROM yourTable;");
cmd.Connection = myCon;
myCon.Open();
try
{
OleDbDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
if (txt_cname.Text.Equals((rdr[0].ToString())))
{
myCon.Close();
return true;
}
}
myCon.Close();
return false;
}
catch (Exception e)
{
MessageBox.Show(e.Message);
myCon.Close();
return false;
}
}
Let me know if it works or the error you get.
working useful code try this
BOMaster obj_data = new BOMaster();
obj_data.productid = tempid;
obj_data.categoryid =int.Parse(cmbcategory.SelectedValue.ToString());
obj_data.productcode = txtproductcode.Text;
obj_data.productname = txtproductname.Text;
obj_data.mqty = decimal.Parse(txtmqty.Text.ToString());
OleDbCommand mycmd = new OleDbCommand("select * from productmaster where productname=?", new OleDbConnection(Common.cnn));
BOMaster obj_datan = new BOMaster();
mycmd.Parameters.Add(new OleDbParameter("productname", txtproductname.Text));
mycmd.Connection.Open();
OleDbDataReader myreader = mycmd.ExecuteReader(CommandBehavior.CloseConnection);
if (myreader.HasRows == true)
{
// savestutus = "false";
MessageBox.Show("Product Name Already Exist", "Product", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtproductname.Focus();
return;
}
mycmd.Connection.Close();
ProductDAL obj_dal = new ProductDAL();
if (obj_dal.Save(obj_data))
{
Clear();
}