I'm tring to search for a value in multiple Sqlite tables and return the row where the value is found.
But my code only works if the value is in the last table i search.
SetConnection();
sql_con.Open();
sql_cmd = sql_con.CreateCommand();
dataGridView1.DataSource = "";
try
{
string comando = "SELECT UFE_SG, lOG_NO FROM log_logradouro where cep ='" + maskedTextBoxCep.Text + "'";
DB = new SQLiteDataAdapter(comando, sql_con);
}
catch (SystemException e)
{
}
try
{
string comando = "SELECT UFE_SG, lOc_NO FROM log_localidade where cep ='" + maskedTextBoxCep.Text + "'";
DB = new SQLiteDataAdapter(comando, sql_con);
}
catch (SystemException e)
{
}
try
{
string comando = "SELECT UFE_SG, CPC_NO FROM log_cpc where cep ='" + maskedTextBoxCep.Text + "'";
DB = new SQLiteDataAdapter(comando, sql_con);
}
catch (SystemException e)
{
}
DS.Reset();
DB.Fill(DS);
DT = DS.Tables[0];
dataGridView1.DataSource = DT;
sql_con.Close();
It looks like you're overwriting the DB object in each try/catch block instead of executing the query and checking for results with each command.
Related
I am trying to delete data from a Database AND the DataGridViewer using Winforms on Visual Studio. The way I am doing this is selecting a cell, and based on where that cell is, that row will be deleted. The selected row will read two strings and one date. I've tested the two strings and they work perfectly when deleting data. When it comes to the date, it doesn't seem to work for me, I keep getting an error. The error message will be attached as an image and the code will be below. I am fairly new to C# and SQL, just to put that out there.
private void delete_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell theCell in daily_log.SelectedCells)
{
if (theCell.Selected)
{
string eid = daily_log[0, theCell.RowIndex].Value.ToString();
string aid = daily_log[4, theCell.RowIndex].Value.ToString();
DateTime dt = Convert.ToDateTime(daily_log[5, theCell.RowIndex].Value);
try
{
connection.Open();
using (OleDbCommand cmd = new OleDbCommand("DELETE FROM DailyLog WHERE EmployeeID='" + eid + "' AND ActivityID = '" + aid + "' AND Date = '" + dt.Date + "'", connection))
{
cmd.ExecuteNonQuery();
}
connection.Close();
daily_log.Rows.RemoveAt(theCell.RowIndex);
}
catch (Exception ex)
{
MessageBox.Show("Err: " + ex);
}
}
}
}
Is this a conversion error? And if so, how would I fix this?
You could try to use OledbParameter to delete data from access database.
Here is a code example you can refer to.
OleDbConnection conn = new OleDbConnection("connstr");
private void button1_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell theCell in dataGridView1.SelectedCells)
{
if (theCell.Selected)
{
string id = dataGridView1[0, theCell.RowIndex].Value.ToString();
string aid = dataGridView1[1, theCell.RowIndex].Value.ToString();
DateTime dt = Convert.ToDateTime(dataGridView1[2, theCell.RowIndex].Value);
try
{
conn.Open();
string sql = "delete from DailyLog where ID=#ID AND AID=#AID AND Date=#Date";
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#ID", id);
cmd.Parameters.AddWithValue("#AID", aid);
cmd.Parameters.AddWithValue("#Date", dt);
cmd.ExecuteNonQuery();
}
dataGridView1.Rows.RemoveAt(theCell.RowIndex);
}
catch (Exception ex)
{
MessageBox.Show("Err: " + ex);
}
}
}
conn.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
conn.Open();
string query = "select * from DailyLog";
OleDbDataAdapter da = new OleDbDataAdapter(query, conn);
OleDbCommandBuilder builder = new OleDbCommandBuilder(da);
var ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
Result:
Your Ids are probably numeric, and Date is a reserved word, so try with:
"DELETE FROM DailyLog WHERE EmployeeID = " + eid + " AND ActivityID = " + aid + " AND [Date] = #" + dt.Date.ToString("yyyy'/'MM'/dd") + "#"
That said, go for using parameters.
{
I want to edit the dataGridView as well as dataBase.
I have an button when i click it after editing the dataGridview it will updated database.
My first row obly updated but others row doesn't.
here is my code
private void button2_Click(object sender, EventArgs e)
{
try
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
string id = row.Cells["Product ID"].Value.ToString();
string name = row.Cells["Product Name"].Value.ToString();
string description = row.Cells["Product Description"].Value.ToString();
string category = row.Cells["Category"].Value.ToString();
string quantity = row.Cells["QTY"].Value.ToString();
string buyPrice = row.Cells["Buy Price"].Value.ToString();
string sellPrice = row.Cells["Sell Price"].Value.ToString();
string date = row.Cells["Date"].Value.ToString();
String query = "UPDATE [Stock List Table3] SET [Product Name] = '" + name + "',[Product Description] = '" + description + "',[Category] = '" + category + "',[QTY] = '" + quantity + "',[Buy Price] = '" + buyPrice + "',[Sell Price] = '" + sellPrice + "',Date = '" + date + "' WHERE [Product ID] = '" + id + "'";
m.Update_By_DataGridView_Information(query);
m.Load_Table1(dataGridView1);
m.Load_Table1(dataGridView4);
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
}
public void Load_Table1(DataGridView dv)
{
string query = "SELECT * FROM [Stock List Table3]";
SqlConnection Conn = create_connection();
SqlCommand cmd = new SqlCommand(query, Conn);
try
{
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
DataTable dataset = new DataTable();
sda.Fill(dataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dataset;
dv.DataSource = bSource;
sda.Update(dataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void Update_By_DataGridView_Information(string query)
{
try
{
SqlConnection Conn = create_connection();
SqlCommand cmd = new SqlCommand(query, Conn);
cmd.ExecuteNonQuery();
Conn.Close();
//MessageBox.Show("Updated Product Information Successfully", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here is my total code Error Line catch block in button2
After updating first row you update datagridview1 with original data
m.Load_Table1(dataGridView1)
Then next rows was updated with same values...
Try to put Load method outside of foreach loop:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
//your update code for row...
}
m.Load_Table1(dataGridView1);
m.Load_Table1(dataGridView4);
I have a problem, when i m login the error is occured that No value given for one or more required parameters.
protected void imgbtn_login_Click(object sender, ImageClickEventArgs e)
{
int UserId = 0;
string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=pathto.mdb;Persist Security Info=False;");
OleDbConnection conn = new OleDbConnection(str);
conn.Open();
string query = "select * from Users where LoginName='" + txt_logname.Text + "' and Password='" + txt_pass.Text + "';";
OleDbDataAdapter da=new OleDbDataAdapter(query,conn);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = new DataTable();
dt = ds.Tables[0];
try
{
UserId = Int32.Parse(dt.Rows[0]["UserId"].ToString());
//btn_LogIn.Text = "Login Succeded";
Response.Redirect("Register.aspx");
}
catch (Exception ex)
{
}
txt_logname.Text = " ";
txt_pass.Text = "";
}
Password is a reserved word. Put it in square brackets [Password]
See Syntax error in INSERT INTO statement
I created a simple code that retrieves a database parameter which is ("SOPNUMBE", ordernumber)
However, sometimes an employee will fill out an incorrect order giving me a "LIFTxxxx" value instead of a SOPNUMBE which is "ORDxxxxx" etc. Since L is before S, my ftp site processes LIFT first creating an error. I would really like to have this application ignore everything besides "SOPNUMBE", I feel this is a pretty simple question and to me it sounds like a simple if then statement. But I am having trouble wording it. Any help would be greatly appreciated!!
public bool UpdateOrderToShipped(string order)
{
orderNumber = order;
string batch = ConfigurationManager.AppSettings["SuccessfulOrderBatch"];
string statement = "UPDATE SOP10100 SET BACHNUMB = '"+ batch +"' WHERE SOPNUMBE = #SOPNUMBE";
SqlCommand comm = new SqlCommand(statement, connectionPCI);
comm.Parameters.Add("SOPNUMBE", orderNumber);
try
{
comm.Connection.Open();
comm.ExecuteNonQuery();
comm.Connection.Close();
}
catch(Exception e)
{
comm.Connection.Close();
KaplanFTP.errorMsg = "Database error: " + e.Message;
}
statement = "SELECT SOPTYPE FROM SOP10100 WHERE SOPNUMBE = #SOPNUMBE";
comm.CommandText = statement;
SqlDataAdapter da = new SqlDataAdapter(comm);
DataTable dt = new DataTable();
da.Fill(dt);
soptype = dt.Rows[0]["SOPTYPE"].ToString();
return true;
}
LAs noted in my comment, if you aren't comfortable changing this code with an if statement, then you probably shouldn't be maintaining this code. (Do you know where else this code is referenced? Your change will be affecting those places.)
But here you go...
public bool UpdateOrderToShipped(string order)
{
if ((String.CompareOrdinal(order, 0, "ORD", 0, 3) == 0)
{
orderNumber = order;
string batch = ConfigurationManager.AppSettings["SuccessfulOrderBatch"];
string statement = "UPDATE SOP10100 SET BACHNUMB = '"+ batch +"' WHERE SOPNUMBE = #SOPNUMBE";
SqlCommand comm = new SqlCommand(statement, connectionPCI);
comm.Parameters.Add("SOPNUMBE", orderNumber);
try
{
comm.Connection.Open();
comm.ExecuteNonQuery();
comm.Connection.Close();
}
catch(Exception e)
{
comm.Connection.Close();
KaplanFTP.errorMsg = "Database error: " + e.Message;
}
statement = "SELECT SOPTYPE FROM SOP10100 WHERE SOPNUMBE = #SOPNUMBE";
comm.CommandText = statement;
SqlDataAdapter da = new SqlDataAdapter(comm);
DataTable dt = new DataTable();
da.Fill(dt);
soptype = dt.Rows[0]["SOPTYPE"].ToString();
return true;
} else
{
return false;
}
}
when i specify values in my update query the query works fine and the database gets updated, but when i use parameters in my query the database does not update
here is the code i have written
try
{
OdbcConnection MyConnection = new OdbcConnection(ConfigurationManager.ConnectionStrings["myconn"].ConnectionString);
MyConnection.Open();
String MyString = "UPDATE orddetpabak SET jud1=#jud1,jud2=#jud2,jud3=#jud3,adv=#adv where fil_no=#fil_no AND orderdate=#orderdate";
OdbcCommand MyCmd = new OdbcCommand(MyString, MyConnection);
String j1=DropDownList4.SelectedValue;
String j2=DropDownList5.SelectedValue;
String j3=DropDownList6.SelectedValue;
String j4=TextBox4.Text;
String j5 = HiddenField1.Value;
String j6 = TextBox3.Text;
MyCmd.Parameters.AddWithValue("#jud1",j1);
MyCmd.Parameters.AddWithValue("#jud2",j2);
MyCmd.Parameters.AddWithValue("#jud3",j3);
MyCmd.Parameters.AddWithValue("#adv",j4);
MyCmd.Parameters.AddWithValue("#fil_no",j5);
MyCmd.Parameters.AddWithValue("#orderdate",j6);
Response.Write(DropDownList4.SelectedValue);
Response.Write(" " + DropDownList5.SelectedValue);
Response.Write(" " + DropDownList6.SelectedValue);
Response.Write(" " + TextBox4.Text);
Response.Write(" " + HiddenField1.Value);
Response.Write(" " + TextBox3.Text);
MyCmd.ExecuteNonQuery();
//MyConnection.Close();
}
catch(Exception epp)
{
Response.Write(epp);
}
Please Help
As far as I know you cannot use named parameters in MySQL. If you change your string to be
String MyString = "UPDATE orddetpabak SET jud1=?,jud2=?,jud3=?,adv=?
where fil_no=? AND orderdate=?";
and your parameters as:
MyCmd.Parameters.AddWithValue("",j1);
MyCmd.Parameters.AddWithValue("",j2);
MyCmd.Parameters.AddWithValue("",j3);
MyCmd.Parameters.AddWithValue("",j4);
MyCmd.Parameters.AddWithValue("",j5);
MyCmd.Parameters.AddWithValue("",j6);
Hope this helps.
It can be like the following: (I'm using the ADO.NET driver for MySQL version 6.3.7.0, latest one had some issues).
public bool UpdateCustomerIAR(IAR oIAR)
{
bool bRetVal = false;
try
{
MySqlConnection dbConnection = new MySqlConnection(APPSConn.ConnectionString);
MySqlCommand dbCommand = dbConnection.CreateCommand();
string szSQL = string.Empty;
szSQL = "UPDATE schema.table_name SET field_name_one=?field_name_one";
szSQL += " WHERE field_name_two=?field_name_two";
using (MySql.Data.MySqlClient.MySqlConnection conn = new
MySql.Data.MySqlClient.MySqlConnection(APPSConn.ConnectionString))
{
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = szSQL;
cmd.Parameters.AddWithValue("?field_name_one", oIAR.Title);
cmd.Parameters.AddWithValue("?field_name_two", oIAR.IARID.ToString());
conn.Open();
cmd.ExecuteNonQuery();
bRetVal = true;
}
return bRetVal;
}
catch (MySqlException ex)
{
ErrorHandler(ex.ToString());
return bRetVal;
}
catch (Exception ex)
{
ErrorHandler(ex.ToString());
return bRetVal;
}
}