Clear with query in MS Access 97 database using C# with date - c#

I created a button with link code to the MS Access 97 database and a delete query, but when I run the code, nothing is deleted from the database. The search must be done on the first column which is id_car which is composed of XXYYYYZZZZ (XX = Month, YYYY = Year, ZZZZ = is a code that doesn't interest me)
string MesePartenza = Mese1;
string MeseFinale = Mese2;
OleDbCommand cmd = new OleDbCommand("DELETE * FROM cartellini WHERE id_car BETWEEN '" + MesePartenza + "" + AnnoP.ToString() + "*' AND '" + MeseFinale + "" + AnnoF.ToString() + "*'", connect);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(cmd);
cmd.ExecuteNonQuery();

Print your finished sql and post it here. Also, you can't use wildcards here. Try:
String sql = "DELETE * FROM cartellini WHERE id_car BETWEEN '" + MesePartenza + AnnoP.ToString() + "0000' AND '" + MeseFinale + AnnoF.ToString() + "ZZZZ'";
Console.WriteLine(sql);
OleDbCommand cmd = new OleDbCommand(sql, connect);

Related

Query doesn't store my registration form data asp.net

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 .

Insert data into table(from select) using 2 DataGridView c# windowsForm

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

C# query with 3 AND conditions

I have 3 combobox that take there information from MS Access database. I want to select data from database according to the values of the combo boxes.
I wrote this query:
string query = "select * from products where category='" + comboBox1.Text + "' and subcategory='" + comboBox2.Text + "' and size='" + comboBox3.Text + "'";
But it gives me the following exception:
IErrorInfo.GetDescription failed with E_FAIL(0x80004005).
Can you help me?
Full code:
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from products where category='" + comboBox1.Text +
"' and subcategory='" + comboBox2.Text + "' and size='" + comboBox3.Text + "'";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
I'm guessing since size is a reserved word in MS Access, it is throwing that error.
See this link for list of reserved words in Access.
Try changing the column name. Also, try to use parameterized query to prevent sql injection.
See this answer on how to use parameterized query in Access.

SQL code for delete Row?

please anyone to explain me what is the problem with following code why didn't delete Table Row.
con.Open();
SqlCommand cmd = new SqlCommand("delete from RentTable where CID = '" + ID + "' and MID = '" + MID + "' )", con);
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
Message = "succsess";
}
else
{
Message = "!";
}
con.Close();
75% of all these types of problems would be fixed if people loaded their queries into a string variable first then printed them out for debugging purposes :-)
You have a closing parenthesis ) at the end of your query which shouldn't be there.
your sql appears to have a closing brace in it without having an opening brace.
change it to
SqlCommand cmd = new SqlCommand(
"delete from RentTable where CID = '" + ID + "' and MID = '" + MID + "'"
, con);
your command is:
SqlCommand cmd = new SqlCommand(
"delete from RentTable where CID = '" + ID + "' and MID = '" + MID + "' )",
con
);
while it should be:
SqlCommand cmd = new SqlCommand(
"delete from RentTable where CID = '" + ID + "' and MID = '" + MID + "' ",
con
);
(you should remove the ")" from your command)
Change row with sql command creation to this:
/* look at this - no need to wrap string values with
apostrophes since you use parameters */
string query = "delete from RentTable where CID = #id and MID = #mid";
/* create command */
SqlCommand cmd = new SqlCommand(query);
/* set parameters */
cmd.Parameters.AddWithValue("#id", ID);
cmd.Parameters.AddWithValue("#mid", MID);
This's not only solve your problem. This'll help you to prevent problems like it in the future if you'll be using parameters instead concatenation.
PS. Also you have "succsess" misspelled if english word was meant ;)

How to write IF SQL statement in C# for retrieving values from database

I have these three columns in UI. In dropdown I have a AllRecords and some other field. I select that AllRecords field and I enter start and end date details.
Now I write a query for that for retrieving the values.
When he select AllRecords, depending upon start and end dates, it have to display OR retrieve the data from database table.
I have written a query if the user will select other values, it looks like this ,
DataTable dt = new DataTable();
string queryStr = "SELECT Day,Date,Name,Task,Hours from TaskManualDetails where Date between '"
+ DateTime.Parse(txtStartDate.Text).ToString("yyyy-MM-dd")
+ "' and '"
+ DateTime.Parse(txtEndDate.Text).ToString("yyyy-MM-dd")
+ "' and Name ='"
+ DropDownList1.Text.ToString()
+ "'";
SqlDataAdapter s1 = new SqlDataAdapter(queryStr, conn);
s1.Fill(dt);
Now the problem is I have to write query for AllRecords.
try this:
DataTable dt = new DataTable();
string queryStr = "SELECT Day,Date,Name,Task,Hours from TaskManualDetails ";
if ( DropDownList1.Text.ToString() != "AllRecords")
queryStr=queryStr+" where Date between '" + DateTime.Parse(txtStartDate.Text).ToString("yyyy-MM-dd") + "' and '" + DateTime.Parse(txtEndDate.Text).ToString("yyyy-MM-dd") + "'"+" and Name ='" + DropDownList1.Text.ToString() + "'";
SqlDataAdapter s1 = new SqlDataAdapter(queryStr, conn);
s1.Fill(dt);
Only a small change in your query
You have to append and Name ='" + DropDownList1.Text.ToString() to the query only if its not AllRecords
Be care about SQL Injection. Use SQLParameter like this:
DataTable dt = new DataTable();
SqlDataAdapter s1 = new SqlDataAdapter();
s1.SelectCommand.Connection = conn;
string queryStr = "SELECT Day,Date,Name,Task,Hours from TaskManualDetails WHERE Date BETWEEN #StartDate AND #EndDate";
s1.SelectCommand.Parameters.AddWithValue("StartDate", DateTime.Parse(txtStartDate.Text).ToString("yyyy-MM-dd"));
s1.SelectCommand.Parameters.AddWithValue("EndDate", DateTime.Parse(txtEndDate.Text).ToString("yyyy-MM-dd"));
if (DropDownList1.Text.ToString() != "AllRecords")
{
queryStr = queryStr + " AND Name = #Name";
s1.SelectCommand.Parameters.AddWithValue("Name", DropDownList1.Text.ToString());
}
s1.SelectCommand.CommandText = queryStr;
s1.Fill(dt);

Categories