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();
}
Related
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);
}
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.
I want save the ID of the selected subjectname in a DataGridView and also the ID of the student whose year level is selected in the combobox. So my reference for getting the student and subject is the school year and the year level. I want to save it in my table Schedule which has Registration_registrationID (FK), Student_studentID (FK), yearlevel and schoolyear:
Here's my code :
private void btn_add_Click(object sender, EventArgs e)
{
string reg = "";
string schoolyear = txt_startYr.Text + "-" + txt_endYr.Text;
MySqlConnection conn, conn1, conn2;
MySqlCommand cmd2;
MySqlDataReader reader, reader1;
List<DataGridViewRow> selectedRows = (from row in dg_subjects.Rows.Cast<DataGridViewRow>() where Convert.ToBoolean(row.Cells[3].Value) == true select row).ToList();
if (selectedRows.Count >= 1)
{
if (MessageBox.Show(string.Format("Are you sure you want to add this subject?", selectedRows.Count), "Confirmation", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
foreach (DataGridViewRow row in selectedRows)
{
try
{
conn = new MySqlConnection(myconn);
conn.Open();
string subject = "Select subjectID from southpoint_school.subject WHERE subject_name = '" + row.Cells[0].Value.ToString() + "';";
MySqlCommand cmd = new MySqlCommand(subject, conn);
reader = cmd.ExecuteReader();
reader.Read();
string subj = reader.GetString("subjectID");
conn.Close();
conn1 = new MySqlConnection(myconn);
conn1.Open();
string query = "Select regID from southpoint_school.registration where yearLevel = '" + cmb_year.Text + "' AND schoolYear = '" + schoolyear + "';";
MySqlCommand cmd1 = new MySqlCommand(query, conn1);
reader1 = cmd1.ExecuteReader();
while (reader1.Read())
{
conn2 = new MySqlConnection(myconn);
reg = reader1.GetString("regID");
string query1 = "INSERT INTO southpoint_school.schedule (Registration_regID, Subject_subjectID, yearLevel, school_year) values ('" + reg + "','" + subj + "','" + cmb_year.Text + "','" + schoolyear + "')";
cmd2 = new MySqlCommand(query1, conn2);
conn2.Open();
cmd2.ExecuteNonQuery();
MessageBox.Show("Successfully Saved");
conn2.Close();
}
conn1.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
else
{
MessageBox.Show("Please select a Subject");
}
}
It doesn't give an error but it does nothing.
//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();
I'm trying to make a search button that when i enter an ID to a Textbox and press it , it goes to my private SQL server database and get the data row referred to that ID , But The exception handler brings me error because of my wrong CommandText .. Here is my Code
private void SearchBtn_Click(object sender, EventArgs e)
{
cn.ConnectionString = Properties.Settings.Default.ConStr;
if (ID.Text == "")
{
MessageBox.Show("Please Enter The ID you would like to search");
}
else
{
SqlCommand com = new SqlCommand();
cn.Open();
SqlParameter user = new SqlParameter("#ID", SqlDbType.Int);
SqlParameter FN = new SqlParameter("#First_Name",SqlDbType.NChar);
SqlParameter LN = new SqlParameter("#Last_Name", SqlDbType.VarChar);
SqlParameter Jb = new SqlParameter("#Job", SqlDbType.VarChar);
SqlParameter Ag = new SqlParameter("#Age", SqlDbType.VarChar);
SqlParameter ph = new SqlParameter("#Phone", SqlDbType.VarChar);
com.Parameters.Add(user);
com.Parameters.Add(FN);
com.Parameters.Add(LN);
com.Parameters.Add(Jb);
com.Parameters.Add(Ag);
com.Parameters.Add(ph);
com.Connection = cn;
Here is my Error :
*com.CommandText = "Search (First_Name,Last_Name,Job,Age,Phone) values('" + FN + "','" + LN + "','" + Jb+ "','" + Ag + "','" + ph + "' from MyList) ";*
user.Direction = ParameterDirection.Input;
FN.Direction = ParameterDirection.Output;
LN.Direction = ParameterDirection.Output;
Jb.Direction = ParameterDirection.Output;
Ag.Direction = ParameterDirection.Output;
ph.Direction = ParameterDirection.Output;
FN.Size = 10;
LN.Size = 10;
Jb.Size = 10;
Ag.Size = 10;
ph.Size = 10;
user.Value = Convert.ToInt32(ID.Text);
try
{
com.ExecuteNonQuery();
FirstName.Text = FN.Value.ToString();
LastName.Text = LN.Value.ToString();
Job.Text = Jb.Value.ToString();
Age.Text = Ag.Value.ToString();
Phone.Text = ph.Value.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
I'm Using Visual Studio 2012 .
Thanks in Advance .
"Search (First_Name,Last_Name,Job,Age,Phone) values('" + FN + "','" + LN + "','" + Jb+ "','" + Ag + "','" + ph + "' from MyList)"
doesn't really look like SQL. Also I'm not quite sure why you're setting loads of parameters you're not using.
Maybe you meant something like
com.CommandText = "SELECT First_Name, Last_Name, Job, Age, Phone FROM MyList WHERE ID=#Id";
com.Parameters.AddWithValue("#Id", ID.Text);
Furthermore if that's your intention, then ExecuteNonQuery is wrong as that's for INSERT, UPDATE and other things that don't return a result.
Command text should be like
com.CommandText = "SELECT First_Name, Last_Name, Job, Age, Phone FROM MyList WHERE ....";
Remove most of your parameters, leave only input ones.
Instead of com.ExecuteNonQuery() use: SqlDataReader reader = command.ExecuteReader(); and using it read your data. Example article is here
Firstly:
"Search (First_Name,Last_Name,Job,Age,Phone) values('" + FN + "','" + LN + "','" + Jb+ "','" + Ag + "','" + ph + "' from MyList)"
Doesn't look like valid SQL to me.
I think you're looking to do something like this:
using (SqlConnection myConnection = new SqlConnection(connString))
{
string oString = " SELECT * from MyList WHERE (id = #id)";
SqlCommand oCmd = new SqlCommand(oString, myConnection);
oCmd.Parameters.Add(new SqlParameter("#id", ID.Text));
myConnection.Open();
string name="";
string lastname ="";
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
name = oReader["name"].ToString(); // replace "name" with the name of the column you want
lastname = oReader["lastname"].ToString();
}
}
myConnection.Close();
return name + lastname;
You can use these values to set the text in your textboxes on your form:
YourNameTextbox.Text = name;
.. etc