I am creating a form page where I need to show data in data grid view. When the user adds any item from the grid view it should be minused from inventory and update inventory when user press add button.
The code that I am using is giving me this exception:
Additional information: Incorrect syntax near '='.
My code:
private void btnMoveItem_Click(object sender, EventArgs e)
{
SqlConnection con2 = new SqlConnection(#"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True");
con2.Open();
String Query1= "DELETE FROM Inventory WHERE id = " + tbID.Text + "";
SqlCommand sqlcmd1 = new SqlCommand(Query1, con2);
sqlcmd1.ExecuteNonQuery();
SqlCommand sqlcmd = new SqlCommand("UPDATE Inventory SET Quantity = #Quantity" +"WHERE id= " + tbID, con2);
sqlcmd.Parameters.AddWithValue("#Item", this.nudQuantity.Text);
sqlcmd.ExecuteNonQuery();
con2.Close();
}
The error is that you concatenate two strings without space between.
But there are many other errors.
All user values should be a sql parameter with correct type.
nudQuantity.Text must be parsed/validated. Maybe id too.
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True";
using (var con2 = new SqlConnection(connectionString))
{
con2.Open();
var Query1 = "DELETE FROM Inventory WHERE id = #id";
var sqlcmd1 = new SqlCommand(Query1, con2);
sqlcmd1.Parameters.AddWithValue("#id", tbID.Text);
sqlcmd1.ExecuteNonQuery();
var sqlcmd = new SqlCommand("UPDATE Inventory SET Quantity = #Quantity WHERE id=#id", con2);
sqlcmd.Parameters.AddWithValue("#id", tbID.Text);
sqlcmd.Parameters.AddWithValue("#Quantity", int.Parse(nudQuantity.Text));
sqlcmd.ExecuteNonQuery();
}
You could also merge these two query in a single one.
This query should be more like what you need.
UPDATE Inventory SET Quantity = Quantity-#Quantity WHERE id=#id;
DELETE FROM Inventory WHERE id = #id AND Quantity <= 0;
But there are no check on product availability here. If #Quantity is greater than Quantity, then no error will be thrown.
Related
When I click on add that data will go to child table and above data go to master table.
Here's a screenshot of the design:
save button click event:
protected void btnsave_Click(object sender, EventArgs e)
{
SqlConnection con2 = new SqlConnection(#"Data Source=GLSPL06-PC\GLSPL06;Initial Catalog=example;User ID=sa;Password=sa#123");
con2.Open();
SqlCommand cd = new SqlCommand("insertmaster", con2);
cd.CommandType = CommandType.StoredProcedure;
cd.Parameters.AddWithValue("#name", txtname.Text.Trim());
cd.Parameters.AddWithValue("#age", txtage.Text.Trim());
cd.Parameters.AddWithValue("#gender", Radiogender.SelectedItem.ToString());
cd.ExecuteNonQuery();
con2.Close();
foreach (GridViewRow item in gv.Rows)
{
SqlConnection con = new SqlConnection(#"Data Source=GLSPL06-PC\GLSPL06;Initial Catalog=example;User ID=sa;Password=sa#123");
con.Open();
string statment = string.Format("insert into child_table ( [relative_name], [relation]) values ('{0}','{1}')", item.Cells[0].Text, item.Cells[1].Text);
SqlCommand cmd = new SqlCommand(statment, con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Close();
}
successmsg.Text = "Data Inserted Successfully";
}
You have to write Sql query as below in your procedure and call your procedure from application:
DECLARE #id INT
INSERT INTO MainPerson VALUES(Name,Age,Male)
SET #id= SCOPE_IDENTITY()
INSERT INTO RelativePerson Values(#id,Name,Relation)
As you have to use the Scope_Identity in order to get the last id inserted to your master table.
Change Your code to this:
SqlConnection con2 = new SqlConnection(#"Data Source=GLSPL06-PC\GLSPL06;Initial Catalog=example;User ID=sa;Password=sa#123");
con2.Open();
SqlCommand cd = new SqlCommand("insertmaster", con2);
cd.CommandType = CommandType.StoredProcedure;
cd.Parameters.AddWithValue("#name", txtname.Text.Trim());
cd.Parameters.AddWithValue("#age", txtage.Text.Trim());
cd.Parameters.AddWithValue("#gender", Radiogender.SelectedItem.ToString());
string id = cd.GetScalar();
con2.Close();
And Change Your insertmaster Procedure to:
Insert into MainTable values(name,age,gender)
Select SCOPE_IDENTITY()
Then you will get the id use that to insert in child table from code.
I'm trying something out but cant figure it out. So what i'm trying is that if the user inputs something inside txtISN and it already exists inside of the database, the record wont be inserted. I also want a error msg to pop up when a record wasnt inserted and when a record is inserted I want an message to pop up saying that the record was inserted succesfully.
Thanks for the help y'all!
string _connStr = #"Data Source = EJQ7FRN; Initial Catalog = BES; Integrated Security = True";
string _query = "INSERT INTO [BES_S] (ISN,Titel,Name) values (#ISN,#Titel,#Name)";
using (SqlConnection conn = new SqlConnection(_connStr))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = _query;
comm.Parameters.AddWithValue("#ISN", txtISN.Text);
comm.Parameters.AddWithValue("#Titel",txtTitel.Text);
comm.Parameters.AddWithValue("#Name", txtName.Text);
try
{
conn.Open();
comm.ExecuteNonQuery();
}
catch (SqlException ex)
{
}
}
}
You need to change your query a bit, but you can use MySql's DUAL keyword to do this:
string _connStr = #"Data Source = EJQ7FRN; Initial Catalog = BES; Integrated Security = True";
string _query = "INSERT INTO [BES_S] (ISN,Titel,Name) ";
_query = _query + " SELECT #ISN, #Titel, #Name FROM DUAL";
_query = _query + " WHERE NOT EXISTS (SELECT ISN WHERE ISN=#ISN)";
using (SqlConnection conn = new SqlConnection(_connStr))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = _query;
comm.Parameters.AddWithValue("#ISN", txtISN.Text);
comm.Parameters.AddWithValue("#Titel",txtTitel.Text);
comm.Parameters.AddWithValue("#Name", txtName.Text);
try
{
conn.Open();
comm.ExecuteNonQuery();
}
catch (SqlException ex)
{
}
}
}
DUAL is like a dummy table that you can use to SELECT from.
Let the database take care of this using a unique constraint/index:
alter table bes_s add constraint unq_bes_ISN unique (ISN);
This will cause the database to generate an error if a duplicate ISN is inserted. You can put one or more columns for the unique constraint (in case this single column is not the exact definition of uniqueness).
I have an Asp.net application on my page the user requests for a user to be removed. This then populates my 'Admin_TaskList' db.
An administrator then goes in the secure area of the site and enters the users name and clicks a button. Upon the confirmation, the user is then deleted from my 'Users' db (already got this working) but I want my 'Admin_TaskList' db 'Status' column to change from 'To Do' to 'Completed'.
As I sad I have the delete bit working but I am struggling updating my other table.
Snippet of code I have tried
conn.Open();
SqlCommand cmd2 = new SqlCommand("UPDATE FROM Admin_TaskList SET Status = 'Complete' WHERE Description = 'Remove User' AND Name = #Name", conn);
cmd2.Parameters.AddWithValue("#Name", txtRemoveUser.Text);
SqlDataReader rd2 = cmd2.ExecuteReader();
conn.Close();
Full code
public void btnRemoveConfirmYes_Click(object sender, EventArgs e)
{
string connection = ConfigurationManager.ConnectionStrings["PaydayLunchConnectionString1"].ConnectionString;
SqlConnection conn = new SqlConnection(connection);
conn.Open();
SqlCommand cmd1 = new SqlCommand("DELETE FROM Users WHERE Name = #Name", conn);
cmd1.Parameters.AddWithValue("#Name", txtRemoveUser.Text);
SqlDataReader rd1 = cmd1.ExecuteReader();
conn.Close();
conn.Open();
SqlCommand cmd2 = new SqlCommand("UPDATE FROM Admin_TaskList SET Status = 'Complete' WHERE Description = 'Remove User' AND Name = #Name", conn);
cmd2.Parameters.AddWithValue("#Name", txtRemoveUser.Text);
SqlDataReader rd2 = cmd2.ExecuteReader();
conn.Close();
txtRemoveUser.Text = "";
Response.Redirect("/AdminSide/TaskList.aspx");
}
Instead of using a SqlDataReader to update a value use SqlCommand.ExecuteNonQuery:
int updated = cmd2.ExecuteNonQuery();
Remember that you need to use ExecuteNonQuery on commands that modify your data like Delete, Insert or Update.
MSDN:
You can use the ExecuteNonQuery to perform catalog operations (for
example, querying the structure of a database or creating database
objects such as tables), or to change the data in a database without
using a DataSet by executing UPDATE, INSERT, or DELETE statements.
The complete method:
int deleted, updated;
string connection = ConfigurationManager.ConnectionStrings["PaydayLunchConnectionString1"].ConnectionString;
using (var conn = new SqlConnection(connection))
{
conn.Open();
string delSql = "DELETE FROM Users WHERE Name = #Name";
using (var cmd = new SqlCommand(delSql, conn))
{
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = txtRemoveUser.Text;
deleted = cmd.ExecuteNonQuery();
}
string updSql = #"UPDATE Admin_TaskList
SET Status = 'Complete'
WHERE Description = 'Remove User'
AND Name = #Name";
using (var cmd = new SqlCommand(updSql, conn))
{
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = txtRemoveUser.Text;
updated = cmd.ExecuteNonQuery();
}
}
SqlConnection conn = new SqlConnection(#"Data Source=SAI\SQLEXPRESS;Initial Catalog=testing;Integrated Security=True;Pooling=False");
conn.Open();
SqlCommand command = new SqlCommand();
string test = "UPDATE attend Year='2014' WHERE Id = '2'";
command = new SqlCommand(test, conn);
command.ExecuteNonQuery();
conn.Close();
Year and id are both varchar. Error is:
Incorrect syntax near 'Year'.
Should be :
UPDATE attend SET Year='2014' WHERE Id = '2'
I am trying to insert data into a database that I have that has a table called EmployeeInfo
The user is prompted to enter a last name and select a department ID (displayed to the user as either marketing or development) The column ID automatically increments.
Here is my Code behind
protected void SubmitEmployee_Click(object sender, EventArgs e)
{
var submittedEmployeeName = TextBox1.Text;
var submittedDepartment = selectEmployeeDepartment.Text;
if (submittedEmployeeName == "")
{
nameError.Text = "*Last name cannot be blank";
}
else
{
System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection("ConnString");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO EmployeeInfo (LastName, DepartmentID ) VALUES ('" + submittedEmployeeName + "', " + submittedDepartment + ")";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
The error I'm recieving is 'Arguement exception was unhandled by user code'
Here is a picture of it.
As requested. More details
If I had enough reputation, I would rather post this as a reply, but it might actually be the solution.
The reason why it stops there is because you are not providing a legit SqlConnection, since your input is: "ConnString", which is just that text.
The connection string should look something like:
const string MyConnectionString = "SERVER=localhost;DATABASE=DbName;UID=userID;PWD=userPW;"
Which in your case should end up like:
System.Data.SqlClient.SqlConnection sqlConnection1 = new System.Data.SqlClient.SqlConnection(MyConnectionString);
Besides that, you should build your connections like following:
using (SqlConnection con = new SqlConnection(MyConnectionString)) {
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = xxxxxx; // Your query to the database
cmd.Connection = con;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
This will do the closing for you and it also makes it easier for you to nestle connections. I did a project recently and did the connection your way, which ended up not working when I wanted to do more than one execute in one function. Just important to make a new command for each execute.