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.
Related
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);
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();
}
I am having trouble with UPDATE and DELETE data in database when working with ASP.NET web form, the code work well with Windows form so I don't know what I did wrong. The code is suppose to update the Gridview with new edited data but when I click edit button, nothing happen to the gridview as well as the datatable.
This is just an exercise that there is no security requirement so I just want to know how to make it work first.
protected void Edit_btn_Click(object sender, EventArgs e)
{
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
SqlCommand command = new SqlCommand();
command.Connection = sqlCon;
command.CommandText = ("UPDATE WareHouse SET [Name] = '" + Name_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
command.CommandText = ("UPDATE WareHouse SET [Number] = '" + Number_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
command.CommandText = ("UPDATE WareHouse SET [Storage] = '" + Storage_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
command.CommandText = ("UPDATE WareHouse SET [Shelf] = '" + Shelf_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
command.CommandText = ("UPDATE WareHouse SET [Brand] = '" + Brand_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM WareHouse", sqlCon);
DataTable ds = new DataTable();
ad.Fill(ds); // Fill t with data from Adapter a
GridView1.DataSource = ds; // Get data from Source t
GridView1.DataBind();
}
and for delete data
protected void Remove_btn_Click(object sender, EventArgs e)
{
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
SqlCommand command = new SqlCommand();
command.Connection = sqlCon;
command.CommandText = "DELETE FROM WareHouse WHERE [Name] = '" + Name_Field.Text + "' AND [Number] = '" + selectedNumber + "' AND [Storage] = '" + selectedStorage + "' AND [Shelf] = '" + selectedShelf + "' AND [Brand] = '" + selectedBrand + "'";
command.ExecuteNonQuery();
clear();
showData();
}
Aside these 2 function, there are other two that do adding and searching from database which also use SqlCommand and they work fine without problem. Is there any problem with my query?
Storage, Shelf and Brand wouldn't be updated since you are updating [Number] to have the value of Number_Field.Text and then comparing with selectedName in where clause.
It will help you a great deal to put all this SQL code in SP with parameters and call it from ASP.Net code.
Ok.I also faced this issue back when I was learning ASP.NET.
But i had a little different env.
I had a datagrid to play with and any updates in datagrid content should reflect back in DB table upon clicking update button.
So I had below query to populate the grid.
Try
Dim UpperCase As String = UCase(HostnameTextBox.Text)
Dim sql As String = "select * from HOST_DETAILS where upper(HOSTNAME) like '%" + UpperCase + "%'"
da = New OracleDataAdapter(sql, conn)
ds.Clear()
da.Fill(ds, "TEST")
DataGridView1.DataSource = ds.Tables(0)
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
And the below one to update the table on the Update button click.
conn.Open()
Try
Dim ocb As New OracleCommandBuilder
ocb = New OracleCommandBuilder(da)
da.Update(ds, "TEST")
MessageBox.Show("Information Updated")
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
conn.Close()
Also make sure DataAdapter da is global and is defined right after public class so it can be accessed from both.
Dim da As New OracleDataAdapter
Hope this helps.
I've currently got a WHERE clause in a SQL string that looks like this:
CmdTxt = CmdTxt + "Where FA.CSE_LAN = '" + UID + "' ";
It eventually culminates in a call to Oracle:
OracleCommand cmd = new OracleCommand(CmdTxt, connection);
cmd.Connection = connection;
cmd.CommandText = CmdTxt;
cmd.CommandType = CommandType.Text;
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(dt);
What I now need to do is change that WHERE logic, so that it first looks at a column called FA.BUILD_CSE_LAN. If that has a value, it will use that column in the WHERE clause.
If it doesn't have a value, it will use the column FA.CSE_LAN in the WHERE clause.
How can I do this? I'm using C# code-behind in an ASP.Net environment against an Oracle 12c database, if any of that is important.
I am no expert on oracle but I would try something like this.
CmdTxt = CmdTxt + "Where FA.BUILD_CSE_LAN = #UID OR ( FA.BUILD_CSE_LAN IS NULL AND FA.CSE_LAN = #UID)";
That way it if your build field is null, no value, it checks the other one.
And declare #UID as a parameter on your command to avoid injection or special character issues.
This doc on Oracle might help: NVL or COALESCE could help here.
CmdTxt = CmdTxt + "Where NVL(FA.BUILD_CSE_LAN, FA.CSE_LAN) = '" + UID + "' ";
or
CmdTxt = CmdTxt + "Where COALESCE(FA.BUILD_CSE_LAN, FA.CSE_LAN) = '" + UID + "' ";
I'm making a class reservation website and having trouble with creating the button.
I would like to customer to insert two details session into two textboxes, session type "class" or "workshop" and date & time and they will be able to see that information from the DataGridView displayed.
Once they hit the "Reserve" button the button will run a query where it'll add the chosen session from Session table to Reservation table. However my code executes with no errors but does not update the "Reservation" table.
here's my code:
OleDbConnection myConnection = GetConnection();
OleDbCommand cmd = myConnection.CreateCommand();
string query = "select COUNT(*) from [Yoga-Session] where [session type] = '" + txt_type.Text + "' and duration = '" + txt_datetime.Text + "';";
OleDbCommand command = new OleDbCommand(query, myConnection);
myConnection.Open();
int rows1 = (Int32)command.ExecuteScalar();
if (rows1 >= 1)
{
cmd = new OleDbCommand("Select session_id from [yoga-session] where [session type] = '" + txt_type.Text + "' and duration = '" + txt_datetime.Text +"';",myConnection);
int classId = (Int32)command.ExecuteScalar();
cmd = new OleDbCommand("select client_id from client where name = '" + Session["[name]"] + "';", myConnection);
int clientID = (Int32)command.ExecuteScalar();
string query1 = "insert into reservation (session_id, client_id, client_name) values ('" + classId + "','" + clientID + "','" + Session["[name]"].ToString() + "');";
cmd = new OleDbCommand(query1, myConnection);
cmd.ExecuteNonQuery();
Response.Write("Reservation successful");
Response.Redirect("reservation.aspx");
myConnection.Close();
}
}
}
int classId = (Int32)cmd.ExecuteNonQuery();
int clientID = (Int32)cmd.ExecuteNonQuery();
You need to use cmd.ExecuteScalar() to get session_id and client_id values. ExecuteNonQuery returns you no of rows affected by the SQL query.
Also see what #Sherantha pointed out.
ExecuteNonQuery() is not for SELECT commands. To get a field value from SELECT command we need to use ExecuteScalar().
Try replacing;
int rows1 = (Int32)command.ExecuteScalar();
Just a small headsup before I compose my real answer (because I don't have rep to comment)
Firstly: Use Prepared Statements. They help immensely in reducing errors from typing SQL queries, as well as a way to prevent SQL Injection Attacks in real-world situations.
Secondly: While not really needed in most database types, it is recommended that a naming convention is strictly uniform in your code.
Well aside from that, I will get to the real answer now.
Looking at the code, I am assuming that classID and clientID are integers, but in your code, it looks like they are parsed as strings due to the ' ' characters. Do not use the characters when inserting integers.
EDIT: is [session type] meant to be [session_type]?
You should use query1 instead of query.
string query1 = "insert into reservation (session_id, client_id, client_name) values ('" + classId + "','" + clientID + "','" + Session["[name]"].ToString() + "');";
cmd = new OleDbCommand(query1, myConnection);// not query but query1
cmd.ExecuteNonQuery();
Response.Write("Reservation successful");
PS: Use sql data reader to select data.
cmd = new OleDbCommand("Select session_id from [yoga-session] where [session type] = '" + txt_type.Text + "' and duration = '" + txt_datetime.Text +"';",myConnection);
SqlDataReader rdr = cmd.ExecuteReader();
int classId = 0;
while (rdr.Read())
{
clientID = Convert.ToInt32(rdr["session_id"]);
}