Incrementing an int during insert - c#

I'm trying to increment an integer in an MS Access table from a c# .net page during insert.
I'm getting a syntax error when attempting the following. Also unsure if I should be using an ExecuteNonQuery() or not?
OleDbCommand cmd = new OleDbCommand("INSERT INTO tblTarget(target,ref) VALUES(#target,(SELECT MAX(ref)+1 FROM tblTarget)", conn);
cmd.Parameters.AddWithValue("#target", TextTitle.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();

You miss a bracket after tblTarget:
OleDbCommand cmd =
new OleDbCommand("INSERT INTO tblTarget(target,ref) VALUES(#target,(SELECT MAX(ref)+1 FROM tblTarget))", conn);
Here is a little review of your code, try using the using pattern:
using(var conn = new Connection())
{
conn.Open();
string sql = "INSERT INTO tblTarget(target,ref) VALUES(#target,(SELECT MAX(ref)+1 FROM tblTarget))";
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.Parameters.AddWithValue("#target", TextTitle.Text);
cmd.ExecuteNonQuery();
}

You're missing a bracket, try:
INSERT INTO tblTarget(target,ref) VALUES(#target,(SELECT MAX(ref)+1 FROM tblTarget))
But I think you are going to have other issues, you need something closer to this:
INSERT INTO tblTarget ( target, ref )
SELECT #target AS Targ, First((SELECT MAX(ref)+1 FROM tblTarget)) AS MaxRef
FROM tblTarget
GROUP BY #target;

The correct way to achieve your goal is
string sql = "INSERT INTO tblTarget (target,ref) " +
"SELECT ?, MAX(ref)+1 FROM tblTarget";
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.Parameters.AddWithValue("#target", TextTitle.Text);
cmd.ExecuteNonQuery();

I would not do the increment by the sql or code, we can use AutoNumber data type for auto increase the value in access.
string sql = "INSERT INTO tblTarget(target) VALUES(#target)";
using(var conn = new Connection())
using(OleDbCommand cmd = new OleDbCommand(sql, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#target", TextTitle.Text);
cmd.ExecuteNonQuery();
}

Related

I want to insert data into two tables using sql and asp.Net

SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=MYDATASOURCE";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert into [Voorraad] values(#IngredientID,
#AantalInVoorraad, #MinimumVoorraad";
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.Text);
cmd.Parameters.AddWithValue("#AantalInVoorraad", txt_aantal.Text);
cmd.Parameters.AddWithValue("#MinimumVoorraad", txt_minimum.Text);
cmd.Connection = con;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into [Ingredient] values(#IngredientID, #IngredientNaam";
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.Text);
cmd.Parameters.AddWithValue("#IngredientNaam", txt_ingredient.Text);
cmd.ExecuteNonQuery();
I want to insert data to the tables Voorraad and Ingredient. In the tables Voorraad there must IngredientID, AantalInVoorraad, MinimumVoorraad and Categorie be in the table after instert.
In the table Ingredient there must be an new Ingredientnaam be made. When i filling in the text boxes and after hitting the button insert i get the error:
System.Data.SqlClient.SqlException: 'Incorrect syntax near '#MinimumVoorraad'.'
Please help me!
I've edited to this:
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert into [Voorraad] values(#IngredientID,
#AantalInVoorraad, #MinimumVoorraad)";
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.ID);
cmd.Parameters.AddWithValue("#AantalInVoorraad", txt_aantal.Text);
cmd.Parameters.AddWithValue("#MinimumVoorraad", txt_minimum.Text);
cmd.Connection = con;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into [Ingredient] values(#IngredientID,
#IngredientNaam)";
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.ID);
cmd.Parameters.AddWithValue("#IngredientNaam", txt_ingredient.Text);
cmd.ExecuteNonQuery();
Does anybody know maybe another way to insert data to multiple tables in the datbase?? I've searched the whole internet for an answer but i can't find the right solution.
Introducing ASP.NET Web Pages - Entering Database Data by Using Forms
cmd.CommandText = "Insert into [Voorraad] (IngredientID, AantalInVoorraad, MinimumVoorraad) values(#IngredientID, #AantalInVoorraad, #MinimumVoorraad)";
and
cmd.CommandText = "insert into [Ingredient] (IngredientID, IngredientNaam) values(#IngredientID, #IngredientNaam)";
Your insert statements are missing the closing bracket for the values.
Add a using Statement for the SQlConnection and SQLCommand, will make it easier to read and debug.
using (SqlConnection con = new SqlConnection(#"Data Source=MYDATASOURCE"))
{
con.Open();
using(SqlCommand cmd = new SqlCommand(
"Insert into [Voorraad] values(#IngredientID, #AantalInVoorraad, #MinimumVoorraad)", con))
{
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.Text);
cmd.Parameters.AddWithValue("#AantalInVoorraad", txt_aantal.Text);
cmd.Parameters.AddWithValue("#MinimumVoorraad", txt_minimum.Text);
cmd.ExecuteNonQuery();
}
using(SqlCommand cmd = new SqlCommand(
"insert into [Ingredient] values(#IngredientID, #IngredientNaam)", con))
{
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.Text);
cmd.Parameters.AddWithValue("#IngredientNaam", txt_ingredient.Text);
cmd.ExecuteNonQuery();
}
}

Adding a Where Clause to a OleDbCommand

I am trying to add a where clause to the following line of code.
the reason for this is because i get the datatable from a dropdown combobox. now i want to filter that table on user name, so that only the user can see their records.
i need help on how to write the where clause into this code.
if you need any more information i will gladding add it.
thank you for any help.
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From ", comboBox1.Text), con);
After Comments
i added the sql injection protection.
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From
#Companydetails where Research_ID = #Researcher_ID"), con);
cmd.Parameters.AddWithValue("#Companydetails", comboBox1.Text);
cmd.Parameters.AddWithValue("#Researcher_ID", usernumber_lab.Text);
but now it is giving me a error saying:
Additional information: Syntax error in query. Incomplete query clause.
is there something else i need to add to finnish this query off?
I would do it as follows;
string query = "Select * from MyTable Where username = #username";
using (OleDbCommand cmd = new OleDbCommand(query, con))
{
cmd.Parameters.Add("#username", OleDbType.VarChar).Value = comboBox1.Text;
}
This way the object will dispose automatically and also you'll be safe from Sql Injection
Please try this
string sql = String.format("Select * From {0} where id = {1}", comboBox1.Text, id);
OleDbCommand cmd = new OleDbCommand(sql,con);
You can just make your sql statement longer:
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From table Where something = something", comboBox1.Text), con);
You don't have to work with multiline or anything. This is only needed in some database managers, but not in a c# sql statement.
If you would like
OleDbCommand cmd = new OleDbCommand(String.Format("Select * From {0} WHERE username='{1}'", comboBox1.Text,username.Text), con);
You can try the below code
OleDbCommand cmd = new OleDbCommand(string.Format(
"SELECT * FROM {0} WHERE Username = '{1}'",
comboBox1.Text, userName), con);

How to insert data into SQL Server?

I have code like this:
con.Open();
cmd = new SqlCommand("insert into Penawaran (ID_Paket,Jenis_Paket,Harga_Paket) Values (#ID_Paket,#Jenis_Paket,#Harga_Paket", con);
cmd.Parameters.AddWithValue("#ID_Paket", txtIDPaket.Text);
cmd.Parameters.AddWithValue("#Jenis_Paket", txtjenisPaket.Text);
cmd.Parameters.AddWithValue("#Harga_Paket", txtHargaPaket.Value); // this is int sir how to insert it, still error i write like this
cmd.ExecuteNonQuery();
con.Close();
Please help me to inside int to my table Paket.
There is a missing parenthesis at the end of Insert query
INSERT INTO Penawaran (ID_Paket,Jenis_Paket,Harga_Paket)
VALUES (#ID_Paket,#Jenis_Paket,#Harga_Paket) --Here
Try this
SqlConnection con = new SqlConnection();
con.Open();
SqlCommand cmd = new SqlCommand("insert into Penawaran (ID_Paket,Jenis_Paket,Harga_Paket) Values (#ID_Paket,#Jenis_Paket,#Harga_Paket", con));
cmd.Parameters.Add("#ID_Paket", SqlDbType.Int);
cmd.Parameters.Add("#Jenis_Paket", SqlDbType.VarChar);
cmd.Parameters.Add("#Harga_Paket", SqlDbType.VarChar); // this is int sir how to insert it, still error i write like this
cmd.Parameters["#ID_Paket"] = int.Parse(txtIDPaket.Text);
cmd.Parameters["#Jenis_Paket"] = txtjenisPaket.Text;
cmd.Parameters["#Harga_Paket"] = txtHargaPaket.Value; // this is int sir how to insert it, still error i write like this
cmd.ExecuteNonQuery();
con.Close();

Add multiple parameters - string values

I have for example this sql command:
string strediska="0003,0005";
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection("****");
cmd = new SqlCommand("select code from table where stred in (#strediskac)", con);
cmd.Parameters.Add(new SqlParameter("#strediskac", strediska));
But result is not right. Have you any idea how I could insert more values in one "variable"?
NOW its OK! Thanks for help. My solution:
cmd = new SqlCommand("select code from table where stred in ("+ strediska +")",con);

Can't get a SQL command to recognise the params added

I've not used basic SQL commands for a while and I'm trying to pass a param to a sproc and the run it. However when I run the code I get a "Not Supplied" error.
Code:
SqlConnection conn1 = new SqlConnection(DAL.getConnectionStr());
SqlCommand cmd1 = new SqlCommand("SProc_Item_GetByID", conn1);
cmd1.Parameters.Add(new SqlParameter("#ID", itemId));
conn1.Open();
cmd1.ExecuteNonQuery();
I'm not really sure why this would fail. Apologies for the basic question, but I'm lost!
Thanks in advance.
You should set the CommandType to StoredProcedure, set the connection and use Parameters.AddWithValue("#ID", itemID)
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Connection = conn1;
cmd1.Parameters.AddWithValue("#ID",itemID);
conn1.Open();
cmd1.ExecuteNonQuery();
If you want to use Parameters.Add() (which is obsolete), here is how you do it (you need to pass the type too)
cmd1.Parameters.Add("#ID", SqlDbType.Int); //string maybe, I don't know
cmd1.Parameters["#ID"].Value = itemID;
This should work:
SqlConnection conn1 = new SqlConnection(DAL.getConnectionStr());
SqlCommand cmd1 = new SqlCommand("SProc_Item_GetByID", conn1);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#ID", itemId);
conn1.Open();
cmd1.ExecuteNonQuery();
And to make your code even better, put your SqlConnection and SqlCommand into using statements, so that they'll be freed automatically at the end of the using block:
using(SqlConnection conn1 = new SqlConnection(DAL.getConnectionStr()))
{
using(SqlCommand cmd1 = new SqlCommand("SProc_Item_GetByID", conn1))
{
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#ID", itemId);
conn1.Open();
cmd1.ExecuteNonQuery();
conn.Close();
}
}

Categories