C#.net Windows Application - Input data check before insert to Database - c#

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

Related

Cannot Fetch the Last_inserted_id in a foreach loop inside another foreach mysql C#

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/

C# update query

I am finding error of No value given for one or required parameter C# update query where ever i try to update my c# access data base here is the code...
hope somebody will be of my assistant..
private void updatebutton_Click(object sender, EventArgs e)
{
try
{
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
string query = "update Emplyeedata set [ID]='" + midbox.Text + "',[Name]='" + mnamebox.Text + "',[Deisgnation]='" + mdesbox.Text + "',[Leave]='" + mleavebox.Text + "'Where [Name]='"+mnamebox.Text+"'";
cmd.CommandText = query;
cmd.ExecuteNonQuery();
con.Close();
cb();
MessageBox.Show("Updated", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
as a bit more improvement you can try like this, and if you can post the full error information.
private void updatebutton_Click()
{
using (OleDbConnection con = new OleDbConnection("Define your Connection String here"))
{
string query = #"UPDATE Emplyeedata
SET [id] = #ID
,[Name] = #Name
,[Deisgnation] = #Deisgnation
,[Leave] = #Leave
WHERE [Name] = #Name";
using (OleDbCommand cmd = new OleDbCommand(query, con) { CommandType = CommandType.Text })
{
cmd.Parameters.AddWithValue("#ID", midbox.Text);
cmd.Parameters.AddWithValue("#Name", mnamebox.Text);
cmd.Parameters.AddWithValue("#Deisgnation", mdesbox.Text);
cmd.Parameters.AddWithValue("#Leave", mleavebox.Text);
cmd.Parameters.AddWithValue("#Name", mnamebox.Text);
con.Open();
cmd.ExecuteNonQuery();
}
con.Close();
}
}
(this is a really unstructured way and please follow the SOLID Principle/s)

How to Save 2 different Cell values into 2 different variables from database C#

I am stuck on collecting 2 column values from a database row.
this method is only working to retrieve one value, not for 2. I need to save values from cells to Different variables then I will use these variables to populate another database.
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True";
using (var con2 = new SqlConnection(connectionString))
{
try
{
con2.Open();
SqlCommand command = new SqlCommand();
command.Connection = con2;
command.CommandText = string.Format("update Inventory set Quantity= Quantity - {0} WHERE id='"+tbItemid.Text+"'", Convert.ToInt32(tbQuantity.Text));
command.ExecuteNonQuery();
con2.Close();
Data();
DData();
con2.Open();
int x = int.Parse(tbQuantity.Text);
SqlCommand cmd1 = new SqlCommand("SELECT Model from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
modelRdr = cmd1.ExecuteReader();
string model = modelRdr["model"].ToString();
con2.Close();
con.Open();
int y = int.Parse(tbQuantity.Text);
SqlCommand cmd2 = new SqlCommand("SELECT Price from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader pricerdr = null;
pricerdr = cmd2.ExecuteReader();
pricerdr.Read();
int price = int.Parse(pricerdr["Price"].ToString());
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Bill values (" + tbItemid.Text + ",'" +model.ToString()+ "',"+price.ToString()+",'"+tbQuantity.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
Data();
}
catch
{
MessageBox.Show("Enter Catagory and Product ID");
}
}
First thing first you should use Parameterized Queries instead of Concatenations. These kind of queries are prone to SQL Injection. You can read both the columns in one command
SqlCommand cmd1 = new SqlCommand("SELECT Model, Price from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
modelRdr = cmd1.ExecuteReader();
string model = modelRdr["model"].ToString();
int price = int.Parse(modelRdr["Price"].ToString());
The complete code with Parameters would look like
string model=String.Empty;
int price = 0;
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True";
using (SqlConnection con2 = new SqlConnection(connectionString))
{
try
{
con2.Open();
using(SqlCommand command = new SqlCommand())
{
command.Connection = con2;
command.CommandText = string.Format("update Inventory set Quantity = Quantity - #qty WHERE id=#id";
command.Parameters.AddWithValue("#id", tbItemid.Text);
command.Parameters.AddWithValue("#qty", Convert.ToInt32(tbQuantity.Text)));
command.ExecuteNonQuery();
Data();
DData();
int x = int.Parse(tbQuantity.Text);
using(SqlCommand cmd1 = new SqlCommand("SELECT Model, Price from Inventory WHERE id=#id"))
{
cmd1.Parameters.AddWithValue("#id", tbItemid.Text);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
model = modelRdr["model"].ToString();
price = int.Parse(modelRdr["Price"].ToString());
}
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Bill values (#id,#model,#price,#qty)";.
cmd.Parameters.AddWithValue("#id", tbItemid.Text);
cmd.Parameters.AddWithValue("#model", model);
cmd.Parameters.AddWithValue("#price", price);
cmd.Parameters.AddWithValue("#qty", tbQuantity.Text);
cmd.ExecuteNonQuery();
}
Data();
}
catch
{
MessageBox.Show("Enter Catagory and Product ID");
}
}
}

how to retrieve integer value from database & store it in integer in .net

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select FromYear from Factory where Cal_ID='" + DropDownList1.SelectedItem.Text + "'";
cmd.Connection = con;
con.Open();
dr = cmd.ExecuteReader();
dr.Read();
d = dr[0].ToString();
//d =(string) Label4.Text;
con.Close();
}
I want integer value from database
try
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select FromYear from Factory where Cal_ID='" + DropDownList1.SelectedItem.Text + "'";
cmd.Connection = con;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
int d = dr.GetInt32(0);
con.Close();
dr.GetInt32(0) should read an int at position 0
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select FromYear from Factory where Cal_ID='" + DropDownList1.SelectedItem.Text + "'";
cmd.Connection = con;
con.Open();
d = GetYear(cmd).ToString();
con.Close();
}
the "dirty" work is done by GetYear :
private const DEFAULT_YEAR = 2000;
private int GetYear(System.Data.IDbCommand command) {
int year = DEFAULT_YEAR;
using (System.Data.IDataReader reader = command.ExecuteReader()) {
if (reader.Read()) {
year = GetIntOrDefault(reader, 0);
}
}
return year;
}
private int GetIntOrDefault(System.Data.IDataRecord record, int ordinal) {
if (record.IsDBNull(ordinal)) {
return DEFAULT_YEAR;
} else {
return record.GetInt32(ordinal);
}
}
string InvAmountQuery = "SELECT InvAmount FROM Registration WHERE Email='" + useremail + "' ";
SqlCommand InvAmountcom = new SqlCommand(InvAmountQuery, conn);
int InvAmount = Convert.ToInt32(InvAmountcom.ExecuteScalar().ToString());

DataRoutines not creating data in Access Database

today, I am trying to use DataRoutines to insert some values into my Access Database. However, it did not work as well as there were no records created. Does anyone know what's wrong with my code?
This is my DataRoutines (dataroutines2) file
public void CreateRecs(string strUserId)
{
OleDbConnection mDB = new OleDbConnection();
mDB.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0;Data source="
+ Server.MapPath("~/App_Data/webBase.accdb");
OleDbCommand cmd; OleDbDataReader rdr;
string strSql;
string strOFlag = "F";
// check to see if there is an active order record
strSql = "SELECT eStatus FROM enrolInfo WHERE eUserId = #UserId "
+ "ORDER BY eEnrolNo DESC;";
cmd = new OleDbCommand(strSql, mDB);
cmd.Parameters.Add("#UserId", OleDbType.Char).Value = strUserId;
mDB.Open();
rdr = cmd.ExecuteReader();
Boolean booRows = rdr.HasRows;
if (booRows) //when booRows is true, there are order records for the user
{
rdr.Read();
if ((string)rdr["eStatus"] != "Ordering") //status of an active order is "Ordering"
{
strOFlag = "M"; //"T" means there is a need to create a new Orders record
}
else { strOFlag = "M"; }
mDB.Close();
if (strOFlag == "M")
{
//insert a new order record
string strStatus = "Ordering";
strSql = "INSERT INTO enrolInfo (eUserId, eStatus) VALUES (#UserId, #Status)";
cmd = new OleDbCommand(strSql, mDB);
cmd.Parameters.AddWithValue("#UserId", strUserId);
cmd.Parameters.AddWithValue("#Status", strStatus);
mDB.Open();
cmd.ExecuteNonQuery();
mDB.Close();
}
//get back order No - this order no is needed when the user buys an item
strSql = "SELECT eEnrolNo FROM enrolInfo WHERE eUserId = #UserId "
+ "ORDER BY eEnrolNo DESC;";
cmd = new OleDbCommand(strSql, mDB);
cmd.Parameters.Add("#UserId", OleDbType.Char).Value = strUserId;
mDB.Open();
rdr = cmd.ExecuteReader();
rdr.Read();
Session["tOrderNo"] = rdr["eEnrolNo"]; //store the active order no in the sOrderNo
mDB.Close();
return;
}
}
This is the code that will route the solution to the DataRoutines file in my Register Page
//prepare Session variables for newly register customer
Session["sFlag"] = "M";
Session["tUserId"] = (string)txtUserId.Text;
Session["tName"] = (string)txtName.Text;
Session["tAddress"] = (string)txtAddress.Text;
Session["tTel"] = (string)txtTel.Text;
Session["tEmail"] = (string)txtEmail.Text;
String strUserId = (string)Session["tUserId"];
DataRoutines2 DRObject = new DataRoutines2();
DRObject.CreateRecs(strUserId);
Thanks for your help

Categories