I am trying to pass both Column name and the Value to be checked in the code at runtime. However I am getting an:
"Invalid Column Name "
Exception. The code is as follows :
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO rezervasyon (Ad,Soyad,TelefonNo,OdaSayisi,KişiSayisi," +
"Ucret,Acıklama,GirisTarihi,CikisTarihi,KayitTarihi) VALUES " +
"(" + isim + ",'" + soyisim + "','" + telefon + "'," +
"'" + oda_sayisi + "','" + kisi_sayisi + "','" + ucret + "'," +
"'" + aciklama + "','" + giris_tar + "','" + cikis_tar + "'," +
"'" + current_tarih + "')";
cmd.ExecuteNonQuery();
con.Close();
You've missed a single quote here " + isim + " and it should be '" + isim + "'. However you should always use parameterized queries to avoid SQL Injection and also to get rid of this kind of errors.
cmd.CommandText = "INSERT INTO rezervasyon (Ad,Soyad,TelefonNo,OdaSayisi,KişiSayisi,Ucret" +
",Acıklama,GirisTarihi,CikisTarihi,KayitTarihi) " +
"VALUES (#isim, #soyisim , ...)";
cmd.Parameters.AddWithValue("#isim", isim);
cmd.Parameters.AddWithValue("#soyisim", soyisim);
//Other parameters
Although specify the type directly and use the Value property is more better than AddWithValue:
cmd.Parameters.Add("#isim", SqlDbType.VarChar).Value = isim;
Can we stop using AddWithValue() already?
After execution result is coming in two select statement. How can get in two different data table by c#?
using (SqlConnection con = new SqlConnection(sqlConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "Exec SPSearchInvoiceList_rjt " + _customerID + "," + _ProjectInchargeID + "," + _projectID +
"," + _invoiceType + ",'" + _projectTypes + "'," + _invoiceAmount + ",'" + _invoiceCode +
"'," + _invoiceStatusID + ",'" + _invoiceDateFrom + "','" + _invoiceDateTo + "','" +
_invoiceRevisedDateFrom + "','" + _invoiceRevisedDateTo + "','" + _invoiceRaiseDateFrom +
"','" + _invoiceRaiseDateTo + "'," + Convert.ToInt32(PageIndex) + 1 + "," + pageSize;
cmd.Connection = con;
con.Open();
var datareader = cmd.ExecuteReader();
con.Close();
}
}
I am trying to do it as above.I am unable to get records but i am able to get data once i execute commandtext in sql server. Please help.
i'm using MySQL Database with my c# application , and the database in server in locally.
In Each function in the application (Button click, etc.) i open the connection and in the end i close it, like this:
private void btn_addAccount_Click(object sender, EventArgs e)
{
try
{
**objConn.Open();**
//
MySqlCommand cmd;
if(from == "bill_Details")
cmd = new MySqlCommand("insert into accounts (acc_Name,acc_Person,acc_Number,acc_Place,acc_Date,cus_Sup) values ('" + txbName.Text + "','" + txbPerson.Text + "','" + txbNumber.Text + "','" + txbPlace.Text + "','" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "',"+ Bill_Details.cus_Sup +")", objConn);
else
cmd = new MySqlCommand("insert into accounts (acc_Name,acc_Person,acc_Number,acc_Place,acc_Date,cus_Sup) values ('" + txbName.Text + "','" + txbPerson.Text + "','" + txbNumber.Text + "','" + txbPlace.Text + "','" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "'," + Suppliers.cus_Sup + ")", objConn);
cmd.ExecuteNonQuery();
**objConn.Close();**
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I felt in this way that the application need more time to open and close the connection !
is't right like that or i have to open the connection in the starting of application and close it when it close !?
string conStr = null;
SqlCommand cmd;
SqlConnection cnn;
string sql = null;
conStr = "Data Source=DELL-PC\\SQLEXPRESS;Initial Catalog=DBMSI;Integrated Security=True";
sql = "insert into CEC_Employee values('"+empid + "','" + name + "','" + fname + "','" + mname + "','" + lname + "','" + address + "','" + postcode + "','" + job + "','" + sdate + "','" + whours + "','" + sph + "','" + spa + "','" + location + "','" + working + "','" + gender + "','" + dob + "','" + pn + "','" + exp + "','" + vtype + "','" + vexp + "','" + qualification + "','" + email + "','" + number + "','" + nin + "','" + sort + "','" + acc + "','" + bank + "','" + nname + "','" + rel + "','" + addkin + "','" + cnokin + "','" + emailkin + "')";
cnn = new SqlConnection(conStr);
try
{
cnn.Open();
cnn = new SqlConnection(conStr);
cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cnn.Open();
MessageBox.Show("Employee Details registered Succesffuly");
// Keeps on moving to the Exception part of the code. Doesn't execute the try portion of the program.
}
catch (Exception ex)
{
MessageBox.Show("Error Occoured - Employee Details were not recorded");
}
Found the code online. Please help to make it work. Thanks!
Hopefully your primary key on CEC_Employee isn't "empid", and if it is set to be an autonumber, like IDENTITY(1,1), the SQL command will fail as it won't let you hand it a primary key value.
This is speculation of course, since you haven't posted the actual exception message or stack trace.
The below code is to insert student details and run 3 stored procedures (all on cmd1). I have used
transaction and rollback for the same. All 4 executenonquery() are executed but nothing is reflected in the database.
Can anyone explain what is wrong or why it is not affecting the database?
con.Open();
SqlCommand cmd1 = con.CreateCommand();
SqlTransaction transaction1;
transaction1 = con.BeginTransaction("Save Update Student");
cmd1.Connection = con;
cmd1.Transaction = transaction1;
try
{
//sp to autogenerate student code in system..
cmd1.CommandText = "sp_AutoGenerateStudentCode";
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.Add("#std", SqlDbType.VarChar).Value = cb_std.SelectedItem.ToString();
cmd1.Parameters.Add("#div", SqlDbType.VarChar).Value = cb_div.SelectedItem;
cmd1.Parameters.Add("#Rollno", SqlDbType.Int).Value = txt_roll.Text;
cmd1.Parameters.Add("#ReturnValue", SqlDbType.VarChar).Value = txt_name.Text;
cmd1.ExecuteNonQuery();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "insert into StudentMaster(GrNo,Name,DOB,Std,Div,RollNo,MobileNo,Address,TelNo,FathersName,FathersProfession,MothersName,MothersProfession,Age,Year,status,DOE,BookNo,FeesStatus,FthrsQlfction,FthrsOfcAdd,FthrsPhone,MthrsPhone,MthrsOfcAdd,MthrsQlfction,Bloodgrp,caste,Nationality,MotherTongue,PreviousSchool,Religion,height,weight,sex,SCode,EmailId)values ('" + txt_Grno.Text + "','" + txt_name.Text + "',#DOB,'" + cb_std.SelectedItem + "','" + cb_div.SelectedItem + "','" + txt_roll.Text + "','" + txt_mobile.Text + "','" + Rtxt_ResiAdd.Text + "','" + txt_Phone.Text + "','" + txt_fname.Text + "','" + txt_fOccu.Text + "','" + txt_mName.Text + "','" + txt_mOccu.Text + "','" + txt_Age.Text + "',getDate(),'" + cb_status.SelectedItem + "',#DOE,'" + txt_bookno.Text + "','" + cb_feestat.SelectedItem + "','" + txt_fQualificatn.Text + "','" + Rtxt_fOfcAdd.Text + "','" + txt_fPhone.Text + "','" + txt_mPhone.Text + "','" + Rtxt_mOfcAdd.Text + "','" + txt_mQualificatn.Text + "','" + cb_BldGrp.SelectedItem + "','" + txt_caste.Text + "','" + txt_Nationality.Text + "','" + txt_MthrTng.Text + "','" + txt_PrevSchool.Text + "','" + txt_Relgn.Text + "','" + masktb_hgt.Text + "','" + masktb_wgt.Text + "','" + cb_Gender.SelectedItem + "','scode','" + txt_email.Text + "')";
cmd1.Parameters.Add("#DOE", SqlDbType.DateTime).Value = dateTimePicker1.Value;
cmd1.Parameters.Add("#DOB", SqlDbType.DateTime).Value = dateTimePicker2.Value;
cmd1.ExecuteNonQuery();
cmd1.CommandText = "PrimaryFeesMainUpdate";
cmd1.ExecuteNonQuery();
cmd1.CommandText = "FEE";
cmd1.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Added Successfully", "Success");
button2_Click(null, null);
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);
// Attempt to roll back the transaction.
try
{
transaction1.Rollback();
}
catch (Exception ex2)
{
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
}
}
con.Close();
Call Commit after you execute the last command:
cmd1.ExecuteNonQuery();
transaction1.Commit();
You must commit your transaction, as follows:
con.Open();
SqlCommand cmd1 = con.CreateCommand();
SqlTransaction transaction1;
transaction1 = con.BeginTransaction("Save Update Student");
cmd1.Connection = con;
cmd1.Transaction = transaction1;
try
{
//sp to autogenerate student code in system..
cmd1.CommandText = "sp_AutoGenerateStudentCode";
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.Add("#std", SqlDbType.VarChar).Value = cb_std.SelectedItem.ToString();
cmd1.Parameters.Add("#div", SqlDbType.VarChar).Value = cb_div.SelectedItem;
cmd1.Parameters.Add("#Rollno", SqlDbType.Int).Value = txt_roll.Text;
cmd1.Parameters.Add("#ReturnValue", SqlDbType.VarChar).Value = txt_name.Text;
cmd1.ExecuteNonQuery();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "insert into StudentMaster(GrNo,Name,DOB,Std,Div,RollNo,MobileNo,Address,TelNo,FathersName,FathersProfession,MothersName,MothersProfession,Age,Year,status,DOE,BookNo,FeesStatus,FthrsQlfction,FthrsOfcAdd,FthrsPhone,MthrsPhone,MthrsOfcAdd,MthrsQlfction,Bloodgrp,caste,Nationality,MotherTongue,PreviousSchool,Religion,height,weight,sex,SCode,EmailId)values ('" + txt_Grno.Text + "','" + txt_name.Text + "',#DOB,'" + cb_std.SelectedItem + "','" + cb_div.SelectedItem + "','" + txt_roll.Text + "','" + txt_mobile.Text + "','" + Rtxt_ResiAdd.Text + "','" + txt_Phone.Text + "','" + txt_fname.Text + "','" + txt_fOccu.Text + "','" + txt_mName.Text + "','" + txt_mOccu.Text + "','" + txt_Age.Text + "',getDate(),'" + cb_status.SelectedItem + "',#DOE,'" + txt_bookno.Text + "','" + cb_feestat.SelectedItem + "','" + txt_fQualificatn.Text + "','" + Rtxt_fOfcAdd.Text + "','" + txt_fPhone.Text + "','" + txt_mPhone.Text + "','" + Rtxt_mOfcAdd.Text + "','" + txt_mQualificatn.Text + "','" + cb_BldGrp.SelectedItem + "','" + txt_caste.Text + "','" + txt_Nationality.Text + "','" + txt_MthrTng.Text + "','" + txt_PrevSchool.Text + "','" + txt_Relgn.Text + "','" + masktb_hgt.Text + "','" + masktb_wgt.Text + "','" + cb_Gender.SelectedItem + "','scode','" + txt_email.Text + "')";
cmd1.Parameters.Add("#DOE", SqlDbType.DateTime).Value = dateTimePicker1.Value;
cmd1.Parameters.Add("#DOB", SqlDbType.DateTime).Value = dateTimePicker2.Value;
cmd1.ExecuteNonQuery();
cmd1.CommandText = "PrimaryFeesMainUpdate";
cmd1.ExecuteNonQuery();
cmd1.CommandText = "FEE";
cmd1.ExecuteNonQuery();
// COMMIT THE TRANSACTION!
transaction1.Commit();
con.Close();
MessageBox.Show("Record Added Successfully", "Success");
button2_Click(null, null);
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);
// Attempt to roll back the transaction.
try
{
transaction1.Rollback();
}
catch (Exception ex2)
{
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
}
}
con.Close();