fatal error encountered during execution... during update - c#

This code is placed in the button. and when i click it to update the data, a messagebox error appears saying "fatal error encountered during command execution".
Your answers would be a great help. Thank you
MySqlConnection connection = new MySqlConnection(MyConnectionString);
MySqlCommand cmd;
try
{
connection.Open();
cmd = connection.CreateCommand();
cmd.CommandText = "UPDATE student_offense SET TYPE=#TYPE,DATE_HAPPENED=#DH,DESCRIPTION=#DESC,SANCTION=#SANC" +
"Where STUDENT_NO = #STUDENT_NO And DESCRIPTION=#DESC And SANCTION=#SANC And DATE_HAPPENED=#DH";
cmd.Parameters.AddWithValue("#TYPE", offense_combo.Text);
cmd.Parameters.AddWithValue("#DH", date_hapen.Text);
cmd.Parameters.AddWithValue("#DESC", description_txt.Text);
cmd.Parameters.AddWithValue("#SANC", sanction_txt.Text);
cmd.Parameters.AddWithValue("#STUDENT_NO", studentNo_txt.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
MessageBox.Show("updated");
//refresh
cmd.CommandText = "SELECT student_info.Student_no,student_info.Lastname,student_info.Firstname,student_offense.Type,student_offense.Description,student_offense.Date_Happened,student_offense.Sanction,student_offense.Date_Recorded from student_info,student_offense where student_info.student_no = student_offense.student_no";
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
dbdataset = new DataTable();
sda.Fill(dbdataset);
bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
student_no_valid.Visible = false;
stud_no_error.Visible = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
listBox1.Items.Clear();
description_txt.Text = "";
studentNo_txt.Text = "";
offense_combo.Text = "";
current_date();
sanction_txt.Text = "";

You are missing space between Parameter #SANC and Where .
Try This:
cmd.CommandText = "UPDATE student_offense SET TYPE=#TYPE,DATE_HAPPENED=#DH,
DESCRIPTION=#DESC,SANCTION=#SANC" + " Where STUDENT_NO = #STUDENT_NO And
DESCRIPTION=#DESC And SANCTION=#SANC And DATE_HAPPENED=#DH";
Suggestion : if your DATE_HAPPENED column type is Date in your table,then You need to send the proper Date format.
Try This: Assuming user enters Date in dd-MM-yyyy format.
DateTime dt = DateTime.ParseExact(date_hapen.Text,"dd-MM-yyyy",
CutureInfo.InvariantCulture);
Now while assigning the DATE_HAPPENED value provide the following format
cmd.Parameters.AddWithValue("#DH",dt.ToString("yyyy-MM-dd"));

Probably this happened at cmd.ExecuteNonQuery(); or in the subsequent query. You can verify this by single-stepping through after a breakpoint. There is probably an error in the SQL. You can find this by looking at the internal error, or by trying the query on MySQL Workbench. Check to see that all of the parameters match table columns, and all the data types match.
Incidentally, there is no need to assign SANCTION and DATE_HAPPENED in the update statement since you required them to be equal in the WHERE.

Related

Search not working properly with datagridview and textboxes

I would like to search for a record through textbox via save button and display searched data in other textboxes and i want to see the searched row in datagrid selected. I managed to solve both codes. but i couldn't mix 2 code and make it 1. sorry for my bad english anyways here are my two codes
//shows searched row in datagridview but does not show in textboxes
SqlCommand cmd = sqlCon.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from cabphase1 where CODENO='"+txtTNo.Text+"'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
sqlCon.Close();
//2nd code: Shows in textbox but not in datagridview
try
{
SqlCommand cmd = new SqlCommand("Select * from cabphase1 where CODENO = '" + txtCODENOAT.Text + "'", sqlCon);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
txtDNAMEAT.Text = dr[0].ToString();
txtLNOAT.Text = dr[1].ToString();
}
else
{
MessageBox.Show("Enter a valid Taxi CODENO - Eg: 31", "FAILED", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error Searching Data" , "Dispatch", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
You don't need to execute the same query against the database. You can use the data retrieved in the first operation to display in the text boxes too.
Also you should not be using string concatenation to generate SQL queries in the code. That is prone to SQL injection. Parameterized queries are highly recommended to protect from SQL injection.
Following code uses the parameterized query.
//shows searched row in datagridview but does not show in textboxes
SqlCommand cmd = sqlCon.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from cabphase1 where CODENO = #codeno";
SqlParameter parameter = new SqlParameter("#codeno", System.Data.SqlDbType.NVarChar);
parameter.Value = txtTNo.Text;
cmd.Parameters.Add(parameter);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
sqlCon.Close();
if(dt.Rows.Count > 0)
{
DataRow row = dt.Rows[0];
txtDNAMEAT.Text = row[0].ToString();
txtLNOAT.Text = row[1].ToString();
}
I hope this will help you solve your issue.

c# Select sql database data using datetimepicker set with date range

I am trying to make c# program, where I have to make a database report to be previewed at the datagridview. Data will be selected using the datetimepicker. I have written the code, it works but then if the date selected is of different months. No records appear
void FilterDBbtnClick(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection();
conn = new MySqlConnection(cs);
string data = "SELECT `Date`, `Process`, `Actual`, `Target` FROM `database` WHERE `Date` BETWEEN '"+this.fromDatePicker.Value+"' AND '"+this.toDatePicker.Value+"' order by `Date` desc";
MySqlCommand cmd = new MySqlCommand(data, conn);
cmd.Connection.Open();
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataSet dt = new DataSet();
sda.Fill(dt);
BindingSource bsource = new BindingSource();
bsource.DataSource = dt;
mondeDataTable.DataSource = dt.Tables[0];
sda.Update(dt);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
cmd.Connection.Close();
}
please help me check my code and tell me what might be wrong or missing.
Use profiler to check the query that hits the DB. I suspect it's a date formatting issue.
Maybe this question can help you with logging the queries that hit the database:
Hope this helps:
Select * from [Table] where StartDate between '06/13/2016' and '10/13/2016'
The above query fetches records between months 06 and 10. Make sure that string in the data variable is in the above format. Also the column type in the database is date.
Check and remove special characters, if any.
Mark this as answer if you find this useful.
Try this for your select query. I have changed one of your select variable because it ambiguous for the Date datatype.
void FilterDBbtnClick(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection();
conn = new MySqlConnection(cs);
//string data = "SELECT `Date`, `Process`, `Actual`, `Target` FROM `database` WHERE `Date` BETWEEN '"+this.fromDatePicker.Value+"' AND '"+this.toDatePicker.Value+"' order by `Date` desc";
//Changed query for getting data from DB according to the date
string data = "SELECT CreatedDate, Process, Actual, Target FROM database WHERE DATE_FORMAT(CreatedDate,'%Y-%m-%d') BETWEEN '"+this.fromDatePicker.Value.ToString("yyyy-MM-dd")+"' AND '"+this.toDatePicker.Value.ToString("yyyy-MM-dd")+"' order by CreatedDate desc";
MySqlCommand cmd = new MySqlCommand(data, conn);
cmd.Connection.Open();
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataSet dt = new DataSet();
sda.Fill(dt);
BindingSource bsource = new BindingSource();
bsource.DataSource = dt;
mondeDataTable.DataSource = dt.Tables[0];
sda.Update(dt);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
cmd.Connection.Close();
}

C# Crystal Report detail loop

I have this loop on my report on c# winform crystal report.
The data repeatedly entered on my report, but when I check on the database it only saved once. Consider that the final value is correct.
try
{
Cursor = Cursors.WaitCursor;
Reports.OfficialReceipt crt = new Reports.OfficialReceipt();
cmd = new MySqlCommand();
MySqlDataAdapter myDA = new MySqlDataAdapter();
DataSet DaTs = new DataSet();
con = new MySqlConnection(cs);
cmd.Connection = con;
cmd.CommandText = "SELECT collection_type.collection_id, collection_type.school_year, collection_type.IDno, collection_type.student_org_desc, collection_type.man_org, collection_type.grand_total, collection_type.tendered_cash, collection_type.payment_change, collection_type.collection_date, student_info.FName, student_info.LName, accounts.name, collection_list.detail, collection_list.unit, collection_list.amount FROM collection_type JOIN collection_list on (collection_type.collection_id = collection_list.collection_id) JOIN accounts on (accounts.id = collection_type.account_id) JOIN student_info on (student_info.IDno = collection_type.IDno) WHERE collection_type.IDno='" + txtIDNo_Collection.Text + "'";
cmd.CommandType = CommandType.Text;
myDA.SelectCommand = cmd;
myDA.Fill(DaTs, "collection_type");
myDA.Fill(DaTs, "student_info");
myDA.Fill(DaTs, "accounts");
myDA.Fill(DaTs, "collection_list");
crt.SetDataSource(DaTs);
Reports.frmSampleForm frm = new Reports.frmSampleForm();
frm.crystalReportViewer1.ReportSource = crt;
frm.Visible = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
There are some fields that you're querying but not showing.
Please drop in the report student_info.LName field.
What do you see? Are there reciepts for many students? Is this what you need?
Run you query to a DB. What is the result you get?

OLEDB Parameterized Query

public void LoadDB()
{
string FileName = #"c:\asdf.accdb";
string query = "SELECT ID, Field1 FROM Table1 WHERE ID=? AND Field1=?";
string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName;
OleDbConnection odc = new OleDbConnection(strConn);
dAdapter = new OleDbDataAdapter();
OleDbCommand cmd = new OleDbCommand(query,odc);
cmd.Parameters.Add("?", OleDbType.Integer, 5).Value = 1234;
cmd.Parameters.Add("?", OleDbType.BSTR, 5).Value ="asdf";
dAdapter.SelectCommand = cmd;
ds = new DataSet();
dAdapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
I'm trying to use parametrized query to bind the access file into the datagridview. It finds the column names fine, but the contents are empty.
How can I fix this issue?
Here is an example of how the parameterized queries work with CSharp, OleDB.
try
{
connw.Open();
OleDbCommand command;
command = new OleDbCommand(
"Update Deliveries " +
"SET Deliveries.EmployeeID = ?, Deliveries.FIN = ?, Deliveries.TodaysOrders = ? , connw);
command.Parameters.Add(new OleDbParameter("#EMPID", Convert.ToDecimal(empsplitIt[1])));
command.Parameters.Add(new OleDbParameter("#FIN", truckSplit[1].ToString()));
command.Parameters.Add(new OleDbParameter("#TodaysOrder", "R"));
catchReturnedRows = command.ExecuteNonQuery();//Commit
connw.Close();
}
catch (OleDbException exception)
{
MessageBox.Show(exception.Message, "OleDb Exception");
}
This will work with any sql statement, you must assign the question mark "?" to each parameter, and then below you must create the parameters and add them in the order of how you laid out the question marks to get the right data into the right field.
In my test program, the ds.Tables[0].Rows.Count datatable actually had 1 row returned (as there was one row in my test database that matched the query itself). If you put a break on this line you should be able to see whether or not data is getting into the datatable in the first place. Try this:
dataGridView1.DataSource = ds.Tables[0];
What does the front end binding of dataGridView1 look like? Running the query in Access could shed some light on the situation too.
Try without specifying column size in parameters:
cmd.Parameters.Add("?", OleDbType.Integer).Value = 1234;
cmd.Parameters.Add("?", OleDbType.BSTR).Value ="asdf";

Retrieving data in DataGridView using SELECT on MySQL

I have a Windows Forms Application. I have to search data from the MySQL database using the "Like" operator. I have used the placeholder (#test, see code below) for the search term but it does not happen.
In simple, I have a TestBox named txtSearch in which I can enter the name of a student partially or completely. I need to retrieve all the entries matching search criteria on DataGrid.
Please check my code below and let me know where I am wrong (Conn String is removed below) :
try
{
dataGridView1.Visible = true;
BindingSource bs = new BindingSource();
DataTable newadm = new DataTable();
String term = txtSearch.Text;
string db = ----Connection String goes here----
bs.DataSource = newadm;
this.dataGridView1.DataSource = bs;
MySqlConnection conn = new MySqlConnection(db);
conn.Open();
string s = "select * from newadm where firstname like '%#term%' OR lastname like '%#term%'";
MySqlCommand cmd = new MySqlCommand(s, conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#term", MySqlDbType.VarChar).Value = txtSearch.Text;
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = new MySqlCommand(s, conn);
da.Fill(newadm);
da.Update(newadm);
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
I get no results in DataGrid using this code(and many variations of it). If I remove the "#Term" place holder, and replace the exact terms, it works.
Please help out. Thanks in advance.
Try,
string s = "select * from newadm where firstname like #term OR lastname like #term";
MySqlCommand cmd = new MySqlCommand(s, conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#term", MySqlDbType.VarChar,40).Value = "%" + txtSearch.Text + "%";

Categories