Error :Transaction is completed ,it is no longer usable - c#

//How to exceute multiple sqlcommands in one transaction in C#..i am using like this but it gives me error..plz let me know what is problem with code..
string[] files = Directory.GetFiles(dir);
foreach (string subfiles in files)
{
con.Open();
SqlTransaction myTrans=null;
myTrans= con.BeginTransaction();
try
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.Transaction = myTrans;
cmd.CommandText = "select descr from genlookup where Code='SS_Purchase_No' and RecId=99998";
SqlDataReader drr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable dt = new DataTable();
//SqlDataAdapter da = new SqlDataAdapter(qry1, con);
DataTable dtw = new DataTable();
dtw.Load(drr);
DataSet dsr = new DataSet();
dsr.Tables.Add(dtw);
//SqlDataAdapter darun = new SqlDataAdapter("select descr from genlookup where Code='SS_Purchase_No' and RecId=99998", con);
//DataSet dsr = new DataSet();
//darun.Fill(dsr);
int run_no = Convert.ToInt32(dsr.Tables[0].Rows[0]["descr"].ToString());
filename = Path.GetFileNameWithoutExtension(subfiles);
string filenames = Path.GetFileName(subfiles);
if (subfiles.Trim().EndsWith(".xlsx"))
{
strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", subfiles);
}
else if (subfiles.Trim().EndsWith(".xls"))
{
strConn = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", subfiles);
}
OleDbConnection exlcon = new OleDbConnection(strConn);
exlcon.Open();
string myTableName = exlcon.GetSchema("Tables").Rows[0]["TABLE_NAME"].ToString();
OleDbDataAdapter oledbadpt = new OleDbDataAdapter(String.Format("SELECT * FROM [{0}] ", myTableName), exlcon);
DataSet d_s = new DataSet();
oledbadpt.Fill(d_s);
exlcon.Close();
for (int i = 7; i < d_s.Tables[0].Rows.Count - 1; i++)
{
PARTNER_ID = d_s.Tables[0].Rows[i]["F1"].ToString();
RTV_LOCTN = d_s.Tables[0].Rows[i]["F3"].ToString();
DateTime date1 = Convert.ToDateTime(d_s.Tables[0].Rows[i]["F13"]);
string ddmm = date1.ToString("yyyyMMdd");
string[] aa = Color_size.Split('/');
// string colr="";
string size = "";
foreach (string ss in aa)
{
size = ss;
}
}
con.Open();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = con;
myCommand.Transaction = myTrans;
myCommand.CommandText = "insert into HSR_Purch_RETURN(PARTNER_ID,RTV_LOCTN)" +
" values('" + PARTNER_ID + "'," + "'" + RTV_LOCTN + "') ";
myCommand.ExecuteNonQuery();
//con.Open();
//SqlCommand cmdd = new SqlCommand(insert, con);
//int value1 = cmdd.ExecuteNonQuery();
//values = string.Empty;
con.Close();
if ((shrwcode != "") && (flag == "F"))
{
string zz = "select DistributionCenter,GLCountry,GLZone,GLState,GLCity from showroommaster where ShowroomCode='" + shrwcode + "'";
SqlDataAdapter da11 = new SqlDataAdapter(zz, con);
DataSet ds11 = new DataSet();
da11.Fill(ds11);
string Dcenter = ds11.Tables[0].Rows[0]["DistributionCenter"].ToString();
string GLCountry = ds11.Tables[0].Rows[0]["GLCountry"].ToString();
string fff = "select isnull(max(EntSrlNo),0)+1 as EntSrlNo from IDTableExtd where ShowroomCode='" + shrwcode + "' and DocDate='" + RTV_DATE + "'";
SqlDataAdapter das = new SqlDataAdapter(fff, con);
DataSet dss = new DataSet();
das.Fill(dss);
SqlCommand extdcmd = new SqlCommand();
extdcmd.Connection = con;
extdcmd.Transaction = myTrans;
string docpre = "PR" + RTV_DATE.Substring(2, 2);
if (dss.Tables[0].Rows.Count > 0)
{
slno = Convert.ToInt32(dss.Tables[0].Rows[0]["EntSrlNo"].ToString());
extdcmd.CommandText = "insert into IDTableExtd (ShowroomCode,TrnType,TrnCtrlNo,DocNoPrefix,docno,DocDate,EntSrlNo,StockNo,DistributionCenter,GLCountry,GLZone,GLState,GLCity,PartyType,PromoValue_LineLevel,DocQty,NetValue,BatchSrlNo)" +
"values ('" + shrwcode + "'," + "'2300'," + "'" + ddmm + "'," + "'" + docpre + "'," + "'" + ddmm + "'," + "'" + RTV_DATE + "'," + "'" + slno + "'," + "'" + TRN_STOCKNO + "'," + "'" + Dcenter + "'," + "'" + GLCountry + "'," + "'" + GLZone + "',"
+ "'" + GLState + "'," + "'" + GLCity + "','10'," + '0' + ",'" + RTV_QTY + "'," + "'" + RTV_cost + "','0')";
con.Open();
// SqlCommand extdcmd = new SqlCommand(instableextd, con);
extdcmd.ExecuteNonQuery();
con.Close();
}
}
}
myTrans.Commit(); ///Error is getting after exceuting this line..

You need refactor your´s code, first, and use something like that:
using (var = new SqlConnection(_connectionstring))
{
try
{
connection.Open();
using(SqlTransaction transaction = connection.BeginTransaction())
{
using (SqlCommand command1= new SqlCommand(commandtext, connection, transaction ))
{
//Do something here
}
using (SqlCommand command2= new SqlCommand(commandtext, connection, transaction ))
{
//Do another stuff here
}
...
transaction .Commit();
}
}
catch (Exception Ex)
{
if (transaction != null) transaction .Rollback();
}
}

(1)As Joseph said refactor your code using Using statement, which helps to dispose the objects properly.
(2)Your code is prone to SQL Injection, so use SQLParameter.
I've shown a sample from your code make it fully.
con.Open();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = con;
myCommand.Transaction = myTrans;
myCommand.CommandText = "insert into HSR_Purch_RETURN(PARTNER_ID,RTV_LOCTN) values(#partnerId,#rtv)";
myCommand.Parameters.Add(new SqlParameter("partnerId",PARTNER_ID));
myCommand.Parameters.Add(new SqlParameter("rtv",RTV_LOCTN));
myCommand.ExecuteNonQuery();
//con.Open();
//SqlCommand cmdd = new SqlCommand(insert, con);
//int value1 = cmdd.ExecuteNonQuery();
//values = string.Empty;
con.Close();

Related

Is there equivalent C# function for "mysqli_fetch_array"?

So I want to manually convert the PHP function to C# Windows Form but I don't know the equivalent function mysqli_fetch_array in C# and how to do array PHP in C#?
I've googling but there is no correct solution.
This is in C# Windows Form
openConnection();
string selectQuery = "SELECT * FROM data_pegawai WHERE is_deleted=0 AND username='" + user + "'";
MySqlCommand command = new MySqlCommand(selectQuery, conn);
MySqlDataReader reader = command.ExecuteReader();
while (valuesList = reader.Read())
{
id = reader.GetInt32("id_peg");
}
closeConnection();
kembali = bayar - subtotal;
lblKembali.Text = kembali.ToString();
string insertQuery1 = "UPDATE data_transaksi SET status_pengerjaan='Lunas',potongan_harga='" + diskonrupiah.ToString() + "',subtotal='" + txtSubtotal.Text + "' WHERE id_transaksi =" + int.Parse(txtID_T.Text);
string insertQuery2 = "INSERT INTO pegawai_onduty VALUES(NULL, '" + id + "','" + txtID_T.Text + "')";
openConnection();
string selectQuery1 = "SELECT dsp.id_spareparts, dtsp.JUMLAH_SPAREPART from data_transaksi dt LEFT JOIN detail_transaksi_sparepart dtsp ON dt.id_transaksi=dtsp.id_transaksi LEFT JOIN spareparts_motor sm ON dtsp.ID_SPAREPARTMOTOR=sm.ID_SPAREPARTMOTOR LEFT JOIN data_spareparts dsp ON sm.id_spareparts=dsp.id_spareparts where dtsp.id_transaksi =" + int.Parse(txtID_T.Text);
MySqlCommand command1 = new MySqlCommand(selectQuery1, conn);
MySqlDataReader reader1 = command1.ExecuteReader();
while (reader1.Read())
{
int getData = "SELECT jumlah_stok FROM data_spareparts dsp WHERE id_spareparts='$jml[0]'";
}
closeConnection();
runQuery(insertQuery1);
runQuery(insertQuery2);
loadTransaksi();
And this is PHP code that I trying to convert to
while($jml=mysqli_fetch_array($dataJumlah))
{
$getData = mysqli_query($conn, "SELECT jumlah_stok FROM data_spareparts dsp WHERE id_spareparts='$jml[0]' ") or die (mysqli_error($conn));
$dataSP = mysqli_fetch_array($getData);
$idSpareparts = $dataSP[0];
$jmlStok = (int) $dataSP[0];
$jmlJual = (int) $jml[1];
$sisaStok = $jmlStok-$jmlJual;
$updateStok = mysqli_query($conn,"UPDATE data_spareparts SET jumlah_stok=$sisaStok WHERE id_spareparts='$jml[0]'") or die (mysqli_error($conn));
}
So I want to do "while($jml=mysqli_fetch_array($dataJumlah))" in C# and the rest of it. But how?
This question has been answered.
Below is the answer
subtotal = Convert.ToDouble(txtSubtotal.Text);
bayar = Convert.ToDouble(txtBayar.Text);
if (bayar < subtotal)
{
MessageBox.Show("Nominal yang dibayarkan lebih kecil dari Subtotal!");
}
else
{
openConnection();
string selectQuery = "SELECT * FROM data_pegawai WHERE is_deleted=0 AND username='" + user + "'";
MySqlCommand command1 = new MySqlCommand(selectQuery, conn);
MySqlDataReader reader1 = command1.ExecuteReader();
while (reader1.Read())
{
id = reader1.GetInt32("id_peg");
}
closeConnection();
kembali = bayar - subtotal;
lblKembali.Text = kembali.ToString();
string insertQuery1 = "UPDATE data_transaksi SET status_pengerjaan='Lunas',potongan_harga='" + diskonrupiah.ToString() + "',subtotal='" + txtSubtotal.Text + "' WHERE id_transaksi =" + int.Parse(txtID_T.Text);
string insertQuery2 = "INSERT INTO pegawai_onduty VALUES(NULL, '" + id + "','" + txtID_T.Text + "')";
openConnection();
string selectQuery1 = "SELECT dsp.id_spareparts, dtsp.JUMLAH_SPAREPART from data_transaksi dt LEFT JOIN detail_transaksi_sparepart dtsp ON dt.id_transaksi=dtsp.id_transaksi LEFT JOIN spareparts_motor sm ON dtsp.ID_SPAREPARTMOTOR=sm.ID_SPAREPARTMOTOR LEFT JOIN data_spareparts dsp ON sm.id_spareparts=dsp.id_spareparts where dtsp.id_transaksi =" + int.Parse(txtID_T.Text);
MySqlCommand command2 = new MySqlCommand(selectQuery1, conn);
MySqlDataReader reader2 = command2.ExecuteReader();
while (reader2.Read())
{
idSparepart = reader2.GetString(0);
jmlJual = reader2.GetInt32(1);
}
closeConnection();
openConnection();
string getData = "SELECT jumlah_stok FROM data_spareparts dsp WHERE id_spareparts='" + idSparepart + "'";
MySqlCommand command3 = new MySqlCommand(getData, conn);
MySqlDataReader reader3 = command3.ExecuteReader();
while (reader3.Read())
{
jmlStok = reader3.GetInt32(0);
}
closeConnection();
sisastok = jmlStok - jmlJual;
string updateStok = "UPDATE data_spareparts SET jumlah_stok = '" + sisastok + "' WHERE id_spareparts ='" + idSparepart + "'";
try
{
openConnection();
MySqlCommand command4 = new MySqlCommand(updateStok, conn);
if (command4.ExecuteNonQuery() == 1)
{
MessageBox.Show("Data berhasil disimpan!");
}
else
{
MessageBox.Show("Data tidak berhasil disimpan!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
closeConnection();
}
runQuery(insertQuery1);
runQuery(insertQuery2);
loadTransaksi();
}

Reducing the lines of code based on conditions

I have 2 if conditions, but with this line of code is getting increased. Can I reduce some code so that it works the same as it is now.
if (ddlProject.SelectedValue != "0" && ddlBuilding.SelectedValue != "0")
{
string queryInsert;
DataTable dtval = new DataTable();
dtval = CF.ExecuteDT("Select BOOKING_NO from xxacl_pN_LEASES_ALL where project_id = '" + ddlProject.SelectedValue + "' and building_id = '" + ddlBuilding.SelectedValue + "'");
for (int i = 0; i < dtval.Rows.Count; i++)
{
string StrSeq = CF.ExecuteScaler("Select xxcus.xxacl_pN_LEASES_ALL_SEQ.next_val from xxacl_pN_LEASES_ALL");
queryInsert = "Insert into xxacl_pN_LEASES_ALL_h select '" + StrSeq + "', SYSDATE FROM xxacl_pn_leases_all where booking_no = '" + dtval.Rows[i]["BOOKING_NO"].ToString() + "'";
OracleConnection conUpdate = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OracleConn"].ToString());
OracleCommand cmd1 = new OracleCommand();
string allQueryUpdate = queryInsert;
cmd1.CommandText = allQueryUpdate;
cmd1.Connection = conUpdate;
conUpdate.Open();
cmd1.ExecuteNonQuery();
}
string queryUpdate;
queryUpdate = "update xxacl_pN_LEASES_ALL set ASSIGNED_TO = '" + ddlSalesUser.SelectedValue + "'";
OracleConnection conUpdate1 = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OracleConn"].ToString());
OracleCommand cmd2 = new OracleCommand();
string allQueryUpdate1 = queryUpdate;
cmd2.CommandText = allQueryUpdate1;
cmd2.Connection = conUpdate1;
conUpdate1.Open();
cmd2.ExecuteNonQuery();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Record updated successfully');window.location ='FrmHoldingCoordinateUpdate.aspx?Redirect=" + Request.QueryString["Redirect"] + "&userid=" + Request.QueryString["userid"].ToString() + "';", true);
}
if (ddlProject.SelectedValue != "0" && ddlBuilding.SelectedValue == "0")
{
string queryInsert;
DataTable dtval = new DataTable();
dtval = CF.ExecuteDT("Select BOOKING_NO from xxacl_pN_LEASES_ALL where project_id = '" + ddlProject.SelectedValue + "' and building_id = '" + ddlBuilding.SelectedValue + "'");
for (int i = 0; i < dtval.Rows.Count; i++)
{
string StrSeq = CF.ExecuteScaler("Select xxcus.xxacl_pN_LEASES_ALL_SEQ.next_val from xxacl_pN_LEASES_ALL");
queryInsert = "Insert into xxacl_pN_LEASES_ALL_h select '" + StrSeq + "', SYSDATE FROM xxacl_pn_leases_all where booking_no = '" + dtval.Rows[i]["BOOKING_NO"].ToString() + "'";
OracleConnection conUpdate = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OracleConn"].ToString());
OracleCommand cmd1 = new OracleCommand();
string allQueryUpdate = queryInsert;
cmd1.CommandText = allQueryUpdate;
cmd1.Connection = conUpdate;
conUpdate.Open();
cmd1.ExecuteNonQuery();
}
string queryUpdate;
queryUpdate = "update xxacl_pN_LEASES_ALL set ASSIGNED_TO = '" + ddlSalesUser.SelectedValue + "'";
OracleConnection conUpdate1 = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OracleConn"].ToString());
OracleCommand cmd2 = new OracleCommand();
string allQueryUpdate1 = queryUpdate;
cmd2.CommandText = allQueryUpdate1;
cmd2.Connection = conUpdate1;
conUpdate1.Open();
cmd2.ExecuteNonQuery();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Record updated successfully');window.location ='FrmHoldingCoordinateUpdate.aspx?Redirect=" + Request.QueryString["Redirect"] + "&userid=" + Request.QueryString["userid"].ToString() + "';", true);
}
Just I am checking the conditions.Rest code is same
I compared the code written in both the if statements using winMerge tool. There is absolutely no difference of even a single bit. You should simply create a private method to enable code reuse in your module. This is how it might look. Without doubt still more refactoring can be done even in the new function UpdateDatabase that I've written to align it to the principles of clean-code.
if (ddlProject.SelectedValue != "0" && ddlBuilding.SelectedValue != "0")
{
UpdateDatabase();
}
if (ddlProject.SelectedValue != "0" && ddlBuilding.SelectedValue == "0")
{
UpdateDatabase();
}
private void UpdateDatabase()
{
string queryInsert;
DataTable dtval = new DataTable();
dtval = CF.ExecuteDT("Select BOOKING_NO from xxacl_pN_LEASES_ALL where project_id = '" + ddlProject.SelectedValue + "' and building_id = '" + ddlBuilding.SelectedValue + "'");
for (int i = 0; i < dtval.Rows.Count; i++)
{
string StrSeq = CF.ExecuteScaler("Select xxcus.xxacl_pN_LEASES_ALL_SEQ.next_val from xxacl_pN_LEASES_ALL");
queryInsert = "Insert into xxacl_pN_LEASES_ALL_h select '" + StrSeq + "', SYSDATE FROM xxacl_pn_leases_all where booking_no = '" + dtval.Rows[i]["BOOKING_NO"].ToString() + "'";
OracleConnection conUpdate = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OracleConn"].ToString());
OracleCommand cmd1 = new OracleCommand();
string allQueryUpdate = queryInsert;
cmd1.CommandText = allQueryUpdate;
cmd1.Connection = conUpdate;
conUpdate.Open();
cmd1.ExecuteNonQuery();
}
string queryUpdate;
queryUpdate = "update xxacl_pN_LEASES_ALL set ASSIGNED_TO = '" + ddlSalesUser.SelectedValue + "'";
OracleConnection conUpdate1 = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OracleConn"].ToString());
OracleCommand cmd2 = new OracleCommand();
string allQueryUpdate1 = queryUpdate;
cmd2.CommandText = allQueryUpdate1;
cmd2.Connection = conUpdate1;
conUpdate1.Open();
cmd2.ExecuteNonQuery();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Record updated successfully');window.location ='FrmHoldingCoordinateUpdate.aspx?Redirect=" + Request.QueryString["Redirect"] + "&userid=" + Request.QueryString["userid"].ToString() + "';", true);
}
Improving upon the above answer, I do not see a need for multiple IF conditions either.
if (ddlProject.SelectedValue != "0")
{
UpdateDatabase();
}
private void UpdateDatabase()
{
string queryInsert;
DataTable dtval = new DataTable();
dtval = CF.ExecuteDT("Select BOOKING_NO from xxacl_pN_LEASES_ALL where project_id = '" + ddlProject.SelectedValue + "' and building_id = '" + ddlBuilding.SelectedValue + "'");
for (int i = 0; i < dtval.Rows.Count; i++)
{
string StrSeq = CF.ExecuteScaler("Select xxcus.xxacl_pN_LEASES_ALL_SEQ.next_val from xxacl_pN_LEASES_ALL");
queryInsert = "Insert into xxacl_pN_LEASES_ALL_h select '" + StrSeq + "', SYSDATE FROM xxacl_pn_leases_all where booking_no = '" + dtval.Rows[i]["BOOKING_NO"].ToString() + "'";
OracleConnection conUpdate = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OracleConn"].ToString());
OracleCommand cmd1 = new OracleCommand();
string allQueryUpdate = queryInsert;
cmd1.CommandText = allQueryUpdate;
cmd1.Connection = conUpdate;
conUpdate.Open();
cmd1.ExecuteNonQuery();
}
string queryUpdate;
queryUpdate = "update xxacl_pN_LEASES_ALL set ASSIGNED_TO = '" + ddlSalesUser.SelectedValue + "'";
OracleConnection conUpdate1 = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OracleConn"].ToString());
OracleCommand cmd2 = new OracleCommand();
string allQueryUpdate1 = queryUpdate;
cmd2.CommandText = allQueryUpdate1;
cmd2.Connection = conUpdate1;
conUpdate1.Open();
cmd2.ExecuteNonQuery();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Record updated successfully');window.location ='FrmHoldingCoordinateUpdate.aspx?Redirect=" + Request.QueryString["Redirect"] + "&userid=" + Request.QueryString["userid"].ToString() + "';", true);
}

how to insert date(long format) into access database using datetimepicker in c# ? (error is in date part only)

Error image is here
the error is in query line , its shows syntax error
try
{
string zero = "0";
DateTime dat = this.dateTimePicker1.Value.Date;
connection1.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection1;
command.CommandText = "insert into client_table(CLIENT, DATE,BILL_AMOUNT, PAID_AMOUNT, BALANCE, CONTACT, ADDRESS )VALUES ('" + txt_client.Text + "', #" + dat.ToLongDateString() + "# ,'" + zero + "','" + zero + "','" + zero + "','" + txt_contact.Text + "','" + txt_address.Text + "')";
command.ExecuteNonQuery();
connection1.Close();
MessageBox.Show("New Client Registration done Successfully.");
connection1.Dispose();
this.Hide();
employee_form f1 = new employee_form("");
f1.ShowDialog();
}
thank you in advance
In Access, dates are delimited by #, not '. Also, Access does not recognize the long date format. But dates are not stored in any format so no worries, change it to:
... + "', #" + dat.ToString() + "# ...etc.
Although if you do not parameterize your query serious damage or data exposure can be done through SQL Injection because someone could type in a SQL statement into one of those textboxes that you are implicitly trusting.
Working example:
class Program
{
static void Main(string[] args)
{
System.Data.OleDb.OleDbConnectionStringBuilder bldr = new System.Data.OleDb.OleDbConnectionStringBuilder();
bldr.DataSource = #"C:\Users\tekhe\Documents\Database2.mdb";
bldr.Provider = "Microsoft.Jet.OLEDB.4.0";
using (System.Data.OleDb.OleDbConnection cnxn = new System.Data.OleDb.OleDbConnection(bldr.ConnectionString))
{
cnxn.Open();
Console.WriteLine("open");
using (System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand())
{
cmd.Connection = cnxn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO [Table1] ([Dob]) VALUES(#" + DateTime.Now.ToString() + "#)";
cmd.ExecuteNonQuery();
}
}
Console.ReadKey();
}
}
Update
However, you want to do something more like this which uses Parameters to protect against SQL Injection which is extremely easy to exploit so do not think that you don't really need to worry about it:
static void Main(string[] args)
{
OleDbConnectionStringBuilder bldr = new OleDbConnectionStringBuilder();
bldr.DataSource = #"C:\Users\tekhe\Documents\Database2.mdb";
bldr.Provider = "Microsoft.Jet.OLEDB.4.0";
using (System.Data.OleDb.OleDbConnection cnxn = new OleDbConnection(bldr.ConnectionString))
{
cnxn.Open();
Console.WriteLine("open");
using (System.Data.OleDb.OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = cnxn;
cmd.CommandType = System.Data.CommandType.Text;
OleDbParameter dobParam = new OleDbParameter("#dob", OleDbType.Date);
dobParam.Value = DateTime.Now;
cmd.Parameters.Add(dobParam);
cmd.CommandText = "INSERT INTO [Table1] ([Dob]) VALUES(#dob)";
cmd.ExecuteNonQuery();
}
}
Console.ReadKey();
}
//code to write date in the access table.
string zero = "0";
DateTime dat = this.dateTimePicker1.Value.Date;
//MessageBox.Show(dat.ToShortDateString());
connection1.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection1;
//command.CommandText = "insert into client_table(DATEE) values( '"dat.ToShortDateString()+"')";
command.CommandText = "insert into client_table (CLIENT, DATEE, BILL_AMOUNT, PAID_AMOUNT, BALANCE, CONTACT, ADDRESS )VALUES ('" + txt_client.Text + "', #"+dat.ToShortDateString()+"# ,'" + zero + "','" + zero + "','" + zero + "','" + txt_contact.Text + "','" + txt_address.Text + "')";
command.ExecuteNonQuery();
connection1.Close();
MessageBox.Show("New Client Registration done Successfully.");
connection1.Dispose();
//New code for receiving the date between two range of dates
try
{
DateTime dat = this.dateTimePicker1.Value.Date;
DateTime dat2 = this.dateTimePicker2.Value.Date;
// MessageBox.Show(dat.ToShortDateString() + " " + dat2.ToShortDateString());
connection1.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection1;
string query;
query = "select * from client_table Where DATEE Between #" + dat.ToLongDateString() +"# and #" + dat2.ToLongDateString() + "# ";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection1.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
Thank you all of you for the support.

How to get multiple dynamic row value into the database using asp.net mvc

public void create(account_detail c, int jobcard_id)
{
SqlConnection con = new SqlConnection(#"Data source =(LocalDB)\v11.0;AttachDbFilename=C:\Users\Wattabyte Inc\Documents\CarInfo.mdf;Integrated Security=True;");
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
string additionalText = string.Empty;
bool needComma = false;
foreach (var details in c.Data)
{
if (needComma)
{
additionalText += ", ";
}
else
{
needComma = true;
additionalText += "('" + jobcard_id + "','" + details.completed_by + "','" + details.reporting_time + "','" + details.cost_activity + "','" + details.spared_part_used + "')";
}
cmd.CommandText = "insert into child_detail values " + additionalText + ";";
cmd.ExecuteNonQuery();
}
I am using this code but it only taking single value but I want to save multiple values into the database. How can I achieve this?
If you need multiple jobcard_id then do this.
Note this is making it fit in your code, I suggest you do some refactoring and figure out a better way to do this because it's just plain ugly.
public void create(account_detail c, List<int> jobcard_ids)
{
SqlConnection con = new SqlConnection(#"Data source =(LocalDB)\v11.0;AttachDbFilename=C:\Users\Wattabyte Inc\Documents\CarInfo.mdf;Integrated Security=True;");
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
string additionalText = string.Empty;
bool needComma = false;
foreach (var details in c.Data)
{
if (needComma)
{
additionalText += ", ";
}
else
{
needComma = true;
foreach(var jobcard_id in jobcard_ids)
{
additionalText += "('" + jobcard_id + "','" + details.completed_by + "','" + details.reporting_time + "','" + details.cost_activity + "','" + details.spared_part_used + "')";
if (jobcard_id != jobcard_ids.Last())
{
// We will need to comma separate the query string unless it's the last item
additionalText+= ",";
}
}
}
cmd.CommandText = "insert into child_detail values " + additionalText + ";";
cmd.ExecuteNonQuery();
}

"Data type mismatch exception" in updating datagridview

I have the following code for update my database. The update works fine but when i try to refresh the data grid view, the programs throws a "data type mismatch in criteria exception"
Here's the code
string gen = "";
if (male_rdbtn.Checked)
gen = "M";
if (female_rdbtn.Checked)
gen = "F";
//Updates the database
OleDbDataAdapter da = new OleDbDataAdapter();
da.UpdateCommand = new OleDbCommand();
da.UpdateCommand.Connection = GetConnection();
da.UpdateCommand.CommandText =
"UPDATE patients SET " +
"firstlastname ='" + nametxt.Text +
"', birthdate='" + birthtxt.Text +
"', birthplace='" + birthcmb.SelectedItem +
"', gender='" + gen +
"', bloodtype='" + bloodcmb.SelectedItem +
"', telnum='" + teltxt.Text +
"', address='" + addresstxt.Text +
"' WHERE patientid=" + txt;
da.UpdateCommand.ExecuteNonQuery();
da.UpdateCommand.Connection.Close();
//My code to refresh data grid view
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = GetConnection();
cmd.CommandText = "SELECT * FROM patients WHERE patientid = '"+ txt +"'";
OleDbDataAdapter dad = new OleDbDataAdapter();
dad.SelectCommand = cmd;
DataSet ds = new DataSet();
dad.Fill(ds, "patients");//mismatch exception is thrown here
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "patients";
cmd.Connection.Close();
}
How can i fix this. Thanks
EDIT: Solved by correcting syntax

Categories