manually increment id in c# from mysql - c#

So I have make an order management system I have use this code to insert my order in data.
xconn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "insert into tblOrder
(RegId,ItmId,quantity,Odrdate,Total) values ('" + label11.Text + "','" +
26 + "','" + txt26.Text + "','" + date + "','" + lbltotal.Text + "');";
cmd.Connection = xconn;
cmd.ExecuteNonQuery();
xconn.Close();
So the order id in my table is auto increment but I want it to only increment after one order is complete.
Once I click total the odrid should increment so that next order gets a new id.

You simply can not insert a new row into a database table without a unique id, if the id is the primary key.
Why dont you introduce a new column „order_status“ in which you store the state of the current order?

Once I click total the odrid should increment so that next order gets
a new id.
What if a orderId is exist for example you click on 993 and you want 994 but it's already exists in database.
As Other suggested you can put a column that have information regarding your +1.
If you are using your current code in production your code can easily hacked using SQL-Injection be careful.

Related

How to check which primary key a record was assigned to in C#?

I'm using the OleDBConnectivity system to connect and use a Microsoft Access database.
I'm adding a record to the table in the database called "PayInfo", and the primary key is automatically set to the next available integer. How do I check what the value of the primary key it was assigned to is? I know this is probably an awful idea, but the only thing I could think of was to re-read the database using the entered values. The issue with this, though it's very unlikely, is that its possible to have 2 identical records stored in the database, their only difference being the primary key, and I need to be able to read the specific one.
My current subroutine for adding the record to the database is as follows:
OleDbCommand command = connection.CreateCommand();
connection.Open();
// The SQL statement:
command.CommandText = "INSERT INTO PayInfo ([UserID], [FullName], [CardType], [CardNo], [CVV], [ExpDate], [Address])" +
"VALUES ('" + Global.UserID.ToString() + "','" + PayInfo[6] + "','" + PayInfo[0] + "','" + PayInfo[1] + "','" + PayInfo[2] + "','" + exp + "','" + adress + "')";
command.Connection = connection;
command.ExecuteNonQuery(); //executes the SQL command.
connection.Close();
return true; //Successful transaction
After executing your insert query, you need to execute another query to get the generated primary key:
command.Parameters.Clear();
command.CommandText = "SELECT ##IDENTITY";
int primaryKey = Convert.ToInt32(Command.ExecuteScalar());
See Microsoft: Retrieving Identity or Autonumber Values for more details:
The Jet database engine does not support the execution of multiple
statements in a batch or the use of output parameters, so it is not
possible to use either of these techniques to return the new
Autonumber value assigned to an inserted row. However, you can add
code to the RowUpdated event handler that executes a separate SELECT
##IDENTITY statement to retrieve the new Autonumber value.

Conversion failed when converting the varchar value 'Batsman' to data type int

This is my C# code - I am running the query
INSERT INTO PM
VALUES ('Ali', '6777777', '3', 'Batsman', 'Fine Player', 'njhuh8obj', 'Lahore');
It is running fine in the database, but not this.
protected void btnAdd_Click(object sender, EventArgs e)//button that add players
{
// for picture to be uploaded
string path = "~/Admin/Players" FileUploadPicture.FileName;
FileUploadPicture.SaveAs(Server.MapPath(path));
SqlCommand cmd = new SqlCommand("INSERT INTO PM VALUES ( '" + TxtPlayerName.Text + "','"+TxtPlayerType.Text + "','" + TxtPlayerBasePrice.Text + "','" + TxtPlayerRecord.Text + "',
'" + ddlCat.SelectedItem.Value + "','" + path + "','" + TxtPlayerAddress.Text + "')", con);//Query of my C# page
// open connection with database
con.Open();
// Command for running query
cmd.ExecuteNonQuery();
con.Close();
// message shown after player is added
Response.Write("<script>alert('**Player Added**')</script>");
}
It seems that there is a problem in code of my C# page not in database, but I am not sure about that.
So please help me to solve this out...
It looks like the second column of your database table accepts an integer value but you are passing a string (TxtPlayerType.Text). If you want to insert an entry with only values for select columns you must specify the column names as follows:
INSERT INTO table_name (Column1, Column2, ...) VALUES (Value1, Value2, ...)
When Column Names aren't specified you must pass values in the order they appear in the database table.
Insert statement should follow the below format
Insert into <TableName>(Column1,Column2) Values (Value1,Value2)
It is good practice to define the column names in the statement as it make sure the order of the columns and also in future if new column added or deleted no need to change the code

look up value from another sql table in c# winforms

I am using c# winform, When the users input something in State field I want to look up that value in another table and find that code. I have commented the line below on what I have tried but that has not worked
MySqlCommand cmdDatabase = new MySqlCommand(" update `STUDENT REGISTER` INNER JOIN `States` ON `STUDENT REGISTER`.`State` = `States`.`State Code` set " +
"`first Name`='" + cboStudentFirstName.Text.Trim() + "'," +
"`Surname`='" + cboStudentSurname.Text.Trim() + "'," +
//if the person selects inputs VIC on this table I want it to look up that value in a table called states and bring me back the code for that state
"STUDENT REGISTER.State= States.State Code," +

Saving Date and Time

I don't know why the date and time is not saving on my Access Database. I follow some tutorial but it seems I'm having some problems on my code.
DateTime getdate = DateTime.Now;
String time = getdate.ToString("F");
and when I add
OleDbCommand cmdInsert = new OleDbCommand(#"insert into TblInventory (ItemCode,ProductName,Quantity,DateTime)
values ('" + txtItem.Text + "','" + txtProduct.Text + "','" + txtQuantity.Text + "','" + time +"')");
cmdInsert.Connection = con;
cmdInsert.ExecuteNonQuery();
Im stock. please help. thanks guys
The error says that there are problem on the insert into statement
Name of your column is DateTime which is a keyword. You need to change name of column. Also use Parameterized query don't concatenate strings in query.
List of reserved words.

dbf file insertion Take a long Time

I use OLEDB to insert data to a DB4 .dbf file. Inserting 13 row takes almost 1 minute which is soooo long, this problem only occurs during insertion in one table, that contain a varchar 20, 2 dates and a decimal. Is there any alternative faster ways to do this?
foreach (DataRow row in fstathotel.Rows)
{
cmd.CommandText = #"insert into fstathote values (" + Convert.ToInt32(row["mpe"]) + ",'" + Convert.ToDateTime(row["date"]) + "','" + row["type"].ToString() + "',?,'" + Convert.ToDateTime(row["edate"]) + "')";
cmd.Parameters.AddWithValue("parmSlot1", Decimal.Parse(row["value"].ToString()));
cmd.ExecuteNonQuery();
}
You are doing cmd.Parameters.AddWithValue in the loop.
This means a parameter is added at each iteration. I do not know about DB4, but I would bet that the OleDB drivers is trying to handle extra additional unused parameters the best it can. It succeeds, but the operation take much more time.
Please insert cmd.Parameters.Clear() like this, and tell if things are running better.
foreach (DataRow row in fstathotel.Rows)
{
cmd.CommandText = #"insert into fstathote values (" + Convert.ToInt32(row["mpe"]) + ",'" + Convert.ToDateTime(row["date"]) + "','" + row["type"].ToString() + "',?,'" + Convert.ToDateTime(row["edate"]) + "')";
cmd.Parameters.Clear(); // Clear the parameter list
cmd.Parameters.AddWithValue("parmSlot1", Decimal.Parse(row["value"].ToString()));
cmd.ExecuteNonQuery();
}
Additionally, I would also try to enclose the loop in a database transaction. Remember that too much indexes on the table are bad for insertion performances.

Categories

Resources