I need to insert data in one table and update id in second table using add button:
private void addButton_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("Insert Into Rent(toolId, customerId, custName, Fee, date, dueDate) Values('" + toolIdComboBx.Text + "', '" + custIdTxtBx.Text + "', '" + custNameTxtBx.Text + "', '" + feeTxtBx.Text + "', '" + dateTimePicker2.Text + "', '" + dateTimePicker1.Text + "')", con);
dr = cmd.ExecuteReader();
if (dr.Read())
{
con.Close();
con.Open();
cmd = new SqlCommand("Update Inventory Set Available = 'No' Where ToolId = = '" + toolIdComboBx.Text + "' ");
cmd.ExecuteNonQuery();
}
con.Close();
DisplayData();
}
I can see a few issues here
Always, always, always use parameterized queries (props to #broots-waymb) and never, ever concatenate user input into a SQL command
Use the using keyword to automatically clean up any object with a Dispose() method, which includes SqlConnection and SqlCommand - this ensures proper cleanup in the presence of exceptions; also it just easier to write correctly
Use ExecuteNonQuery() if you're not expecting a recordset to be returned. As #jdweng pointed out the only query that returns a recordset is a SELECT statement (stored procedures might also). The meaning of Read() is this code is unclear, my guess is that it will always return false
Be careful when your database schema contains one table (Inventory) whose state is dependent on the state of another table (Rent). Consider strategies to avoid this, but if you can't, then you should consider wrapping the update to both tables in a database transaction to make sure the state of your system is consistent
You cannot close a connection if it has a open SqlDataReader.
Why do you read from an INSERT statement? What do you expect?
Also, use parameterized queries.
Update
There is no result value from INSERT, so use ExecuteNonQuery() instead. That way, the connection is available for the next SqlCommand
Thanks guys! I figured it out
con.Open();
using (cmd = new SqlCommand("Insert Into Rent(toolId, customerId, custName,
Fee, date, dueDate) Values('" + toolIdComboBx.Text + "', '" + custIdTxtBx.Text + "', '" +
custNameTxtBx.Text + "', '" + feeTxtBx.Text + "', '" + dateTimePicker2.Text + "', '" +
dateTimePicker1.Text + "')", con))
{
cmd.ExecuteNonQuery();
}
using (cmd = new SqlCommand("Update Inventory Set Available = 'No' Where ToolId = '" + toolIdComboBx.Text + "' ", con))
{
cmd.ExecuteNonQuery();
};
con.Close();
DisplayData();
Related
I'm new joined this site. I have a little bit of a C# problem. I need to know how to insert data into multiple SQL Server tables using C#. English is not my mother language, so sorry if there are some spelling mistakes.
This is my C# code
try
{
Sqlconn.Open();
SqlCommand cmd = Sqlconn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into New_Vehicle values ('" + txt_id.Text + "', '" + txtV_No.Text + "', '" + txtE_No.Text + "', '" + dtm_Year.Text + "')";
cmd.ExecuteNonQuery();
cmd.CommandText = "insert into New_Brand values ('" + txt_id.Text + "', '" + txtB_Name.Text + "', '" + txt_Model_Name.Text + "', '" + txtV_Type.Text + "')";
cmd.ExecuteNonQuery();
Sqlconn.Close();
MessageBox.Show("Seve Record Succesfull", "Insert Message");
}
catch (Exception EX)
{
MessageBox.Show("Error" + EX);
}
This is the error I get when I run this code. Please help how to fix this problem
I would loop through each table with a foreach loop and run the insert code you have there but use the table name from the foreach loop
for this to work, you would need a list of table objects, each with a property called "Name" which contains the name of the table that matches the table name in the database
foreach (var table in List_Of_Tables)
{
cmd.CommandText = "insert into " + table.Name + " values ('" + txt_id.Text + "', '" + txtV_No.Text + "', '" + txtE_No.Text + "', '" + dtm_Year.Text + "')";
cmd.ExecuteNonQuery();
}
I actually new in asp.net c# I want to know why this code below doesn't work.
All I want to do is store data form into a SQL Server database.
I have 2 tables and I want the data form entered stored in the database. Look at the select statement for retrieving the primary key to store it as a foreign key in the other table
String q = "Insert into dbo.requests(request_date,request_type,visit_date,reason,user_id,status_id)values('" + DateTime.Now.ToString() + "','" + DropDownList1.SelectedValue.ToString() + "','" + TextBox8.Text.ToString() + "','" + TextBox9.Text.ToString() + "','"+ 1+"','"+ 2+"')";
SqlCommand cmd = new SqlCommand(q, con);
cmd.ExecuteNonQuery();
con.Close();
con2.Open();
if (con2.State == System.Data.ConnectionState.Open)
{
String a = "select top 1 request_id from dbo.requests where request_date= CAST(GETDATE() AS DATE and user_id=999 order by request_id DESC ";
SqlCommand cmd2 = new SqlCommand(a, con2);
int r = cmd2.ExecuteNonQuery();
}
con2.Close();
con3.Open();
if (con3.State == System.Data.ConnectionState.Open)
{
String b = "INSERT into dbo.visitor(visitor_Fname,visitor_Mname,visitor_family_name,visitor_id,visitor_mobile,request_id,place_of_work,country_name) values ('" + TextBox1.Text.ToString() + "','" + TextBox2.Text.ToString() + "','" + TextBox3.Text.ToString() + "','" + TextBox4.Text.ToString() + "' , '" + TextBox5.Text.ToString() + "','r', '" + TextBox6.Text.ToString() + "', '" + TextBox7.Text.ToString() + "' )";
SqlCommand cmd3 = new SqlCommand(b, con3);
cmd3.ExecuteNonQuery();
}
You should change it
int r = cmd2.ExecuteNonQuery();
to
int r = (int)cmd2.ExecuteScalar();
To retrieve selecting only one field use ExecuteScalar instead of ExecuteNonQuery. ExecuteNonQuery doesn't return selecting fields.
Just store request_id in variable using data table.
Actually you are storing 'r' in table which is wrong. Try to store request_id from select statement in variable it will be work .
Please help me to understand where I go wrong. ok let's go!
2 DataGridViews, in first I'm store services in second order list.
when I push button Save, this code will happen:
public void insert_sales_list()
{
conn.Open();
foreach (DataGridViewRow row in dgvService.SelectedRows)
{
SQLiteCommand cmd = new SQLiteCommand("insert into sales_list (sales_created_date, sales_created_name, emp_name, cust_phone, cust_name, planned_date, planned_time, service_name, discount, price, order_id) values (#ocd, #ocn, #emp, #c_phone, #c_name, #p_date, #p_time, #sn, #disc, #price, #o_id)", conn);
cmd.Parameters.AddWithValue("#ocd", DateTime.Now);
cmd.Parameters.AddWithValue("#ocn", lblLoginUser.Text);
cmd.Parameters.AddWithValue("#emp", dgvOrderList.CurrentRow.Cells[1].Value.ToString());
cmd.Parameters.AddWithValue("#c_phone", dgvOrderList.CurrentRow.Cells[2].Value.ToString());
cmd.Parameters.AddWithValue("#c_name", dgvOrderList.CurrentRow.Cells[3].Value.ToString());
cmd.Parameters.AddWithValue("#p_date", dgvOrderList.CurrentRow.Cells[5].Value);
cmd.Parameters.AddWithValue("#p_time", dgvOrderList.CurrentRow.Cells[6].Value.ToString());
cmd.Parameters.AddWithValue("#sn", row.Cells[0].Value.ToString());
cmd.Parameters.AddWithValue("#disc", dgvOrderList.CurrentRow.Cells[4].Value.ToString());
cmd.Parameters.AddWithValue("#price", row.Cells[1].Value.ToString());
cmd.Parameters.AddWithValue("#o_id", dgvOrderList.CurrentRow.Cells["order id"].Value);
cmd.ExecuteNonQuery();
string sql = "update order_list set status = 'Saved' where id = '" + dgvOrderList.CurrentRow.Cells["order id"].Value + "'";
cmd = new SQLiteCommand(sql, conn);
cmd.ExecuteNonQuery();
}
conn.Close();
By this code you see that I just insert data from Order List to Sales List, user choose service or services from DataGridView.Service, he can take any service from the list.
This code works very well.
Next step. I have another table where each service have own materials, for example - men's haircut have soap, shampoo and tissue paper in materials. And I need to insert these data in SalesMaterials Table. And I think code is wrong, please help me to find this error? code:
public void insert_sales_materials()
{
conn.Open();
foreach (DataGridViewRow row in dgvService.SelectedRows)
{
string Query = "insert into sales_list_materials(order_id, material_id, norma, created_name, creation_date) " +
"values( select '" + dgvOrderList.CurrentRow.Cells["order id"].Value + "', a.material_id, a.norma, '" + lblLoginUser.Text + "', '" + DateTime.Now + "' from service_materials a where a.service_id = '" + row.Cells[2].Value + "')";
SQLiteCommand cmd = new SQLiteCommand(Query, conn);
cmd.ExecuteNonQuery();
}
conn.Close();
}
Error:
Additional information: SQLite error
near "select": syntax error
Ok I got it!
when you insert data with select, please did not use word values =))
correct code for all of you:
public void insert_sales_materials()
{
conn.Open();
foreach (DataGridViewRow row in dgvService.SelectedRows)
{
string Query = "insert into sales_list_materials(order_id, material_id, norma, created_name, creation_date) " +
"select '" + dgvOrderList.CurrentRow.Cells["order id"].Value + "', a.material_id, a.norma, '" + lblLoginUser.Text + "', '" + DateTime.Now + "' from service_materials a where a.service_id = '" + row.Cells[2].Value + "'";
SQLiteCommand cmd = new SQLiteCommand(Query, conn);
cmd.ExecuteNonQuery();
}
conn.Close();
}
layout and db
if (!(string.IsNullOrEmpty(b.ToString())))
{
string connection = "server=127.0.0.1; database=accounts;user=root; password='';";
MySqlConnection conn = new MySqlConnection(connection);
conn.Open();
string SQL = "INSERT INTO payment_voucher (voucher_no, paid_to, date, account_cr, account_dr, description, student_emp_id, amount, total ) values ('" + label8.Text.ToString() + "','" + textBox1.Text + "', '" + dateTimePicker1.Value + "','" + a + "','" + b + "', '" + richTextBox1.Text + "', '" + textBox3.Text + "', '" + textBox4.Text + "', '" + label11.Text.ToString() + "');";
MySqlCommand command = new MySqlCommand(SQL, conn);
command.ExecuteNonQuery();
conn.Close();
}
i dont know why it is happening. front end is in C#.
That statement will not insert two rows.
You have a few things to check here:
Check if that code is being called twice
Check if there is other similar code that is also being called
Make sure there are no triggers on the table that do an additional insert
Make sure you don't have some weird Try/Catch/Fail logic that causes that entire thing to be run again
And most importantly:
Run a SQL Profiler trace to see exactly what is being sent to the database
Query the table when you've checked those with a raw SELECT query in Enterprise Manager and make sure there is one row.
That code above would not duplicate rows unless called twice.
I'm trying to pass a value from my SQL query count() to c# int Tech_Count but it's displaying different. If I only run the query count, it return 3 but in c#, it's showing -1. Here's my code.
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;Integrated Security=True; AttachDbFilename=C:\Users\anthonyhau\Documents\Lawn Mower\LawnMowerDatabase\LawnMowerDatabase\Database1.mdf");
con.Open();
SqlCommand cmd1 = new SqlCommand("update Tech set Customer_Count = (select IdAndCnt.cnt from (select Tech_Id,count (Tech_id) as cnt from Customers group by Tech_Id ) as IdAndCnt where Tech.Tech_Id = IdAndCnt.Tech_Id)", con);
SqlCommand cmd = new SqlCommand("INSERT INTO Customers (First_Name, Last_Name, Street, City, State, Zip, Phone, Date_Started) VALUES ('" + textBox1.Text + "', '" + textBox2.Text + "', '" + textBox3.Text + "', '" + textBox4.Text + "', '" + textBox5.Text + "', '" + textBox6.Text + "', '" + textBox7.Text + "', '" + dateTimePicker1.Value.ToString("MM/dd/yyyy") + "')", con);
SqlCommand techcnt = new SqlCommand("Select count(Tech_Id) From Tech", con);
cmd1.ExecuteNonQuery();
cmd.ExecuteNonQuery();
int Tech_Count = techcnt.ExecuteNonQuery();
textBox8.Text = Tech_Count.ToString();
con.Close();
I think you have to use ExecuteScalar instead of executenonquery and it will solve your problem.
int Tech_Count = (int)techcnt.ExecuteScalar();
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx
That's because ExecuteNonQuery does not return the count like that for SELECT statements:
From MSDN
For UPDATE, INSERT, and DELETE statements, the return value is the
number of rows affected by the command. When a trigger exists on a
table being inserted or updated, the return value includes the number
of rows affected by both the insert or update operation and the number
of rows affected by the trigger or triggers. For all other types of
statements, the return value is -1.
Why are you using ExecuteNonQuery if you are in fact executing a query?? Objects in classes are pretty self explanatory. ExecuteNonQuery is used for update,deletes and inserts so it returns the affected rows. Try this on for size:
SqlCommand techcnt = new SqlCommand("Select #count:=count(Tech_Id) From Tech", con);
techcnt.Parameters.Add("#count", SqlDbType.Int).Direction = ParameterDirection.Output;
techcnt.CommandType = CommandType.Text;
techcnt.ExecuteScalar();
textBox8.Text = techcnt.Parameters["#count"].Value.ToString();
or something shorter like this:
SqlCommand techcnt = new SqlCommand("Select count(Tech_Id) From Tech", con);
textBox8.Text = techcnt.ExecuteScalar().ToString();