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();
Related
I am trying to load csv into my database but I keep getting the following exception
Message=Incorrect syntax near ')'
My code block is as shown below.
var lineNumber = 0;
using (SqlConnection conn = new SqlConnection(#"Data Source=DESKTOP-3EHXXXX;Initial Catalog=XXX_XXXX_Monitoring;Integrated Security=True"))
{
conn.Open();
using (StreamReader reader = new StreamReader(#"C:\\Users\\xxx\\Documents\\XXX\\XXX DATA\\xxxxx_xxxx_2011.csv"))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if(lineNumber !=0)
{
var values = line.Split(',');
Console.WriteLine("Before DB Insertion");
var sql = "INSERT INTO XXXXXXX_Monitoring.dbo.LimsDataLists VALUES ('" + values[0] + "','" + values[1] + "','" + values[2] + "','" + "','" + values[3] + "','" + values[4] + "','" + values[5] + "','" + values[6] + "','" + values[7] + "','" + values[8] + "','" +
values[9] + "','" + values[10] + "','" + values[11] + "','" + values[12] + "','" + values[13] + "','" + values[14] + "','" +
values[15] + "','" + values[16] + "','" + values[17] + "','" + values[18] + "','" + values[19] + "','" + values[20] + "','" +
values[21] + "','" + values[22] + "','" + values[23] + "','" + values[24] + "','" + values[25] + "','" + values[26] + "','" +
values[27] + "','" + values[28] + "','" + values[29] + "','" + values[30] + "','" + values[31] + "','" + values[32] + "','" +
values[33] + "','" + values[34] + "','" + values[35] + "','" + values[36] + "','" + values[37] + "'," + values[38] + ")";
var cmd = new SqlCommand();
cmd.CommandText = sql;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = conn;
cmd.ExecuteNonQuery();
}
lineNumber++;
}
}
conn.Close();
}
Console.WriteLine("Data import Complete!");
Console.ReadLine();
If you don't want to use EF you can use SqlParameter instead plain query text:
var sqlParams = new List<object>();
var valuesList = new List<string>();
for (int i = 0; i < values.Length; i++)
{
sqlParams.Add(new SqlParameter($"#Value{i}", values[i]));
valuesList.Add($"#Value{i}");
}
var sql = $"INSERT INTO EMR_LIMS_Monitoring.dbo.LimsDataLists VALUES ({ string.Join(", ", valuesList)})";
cmd.Parameters.AddRange(sqlParams);
I suspect that error lies in the sql variable. So, you need to debug your code to catch the string value that the sql variable has. And then run the sql string value somewhere in SQL IDE. Hope that this way you will find where he got stuck into; it's probably a syntax error in your INSERT INTO query.
My code doesn't catch the exception when I try to add the same user to the database and I don't really know how to change it.
try
{
SqlConnection.Open();
string sqlZapytanie = "INSERT INTO Host Values('" + host.Name + "','" +
host.Surname + "'," + host.PESEL + ",'" + host.City + "','" + host.Street + "', '" + host.House_number + "','" + host.Apartament_number + "','" + host.e_mail + "'," + host.Phone_number + ",'"+host.Login+"')";
try
{
SqlCommand.Connection = SqlConnection;
SqlCommand.CommandText = sqlZapytanie;
SqlCommand.ExecuteNonQuery();
}
catch(SqlException sqlex)
{
MessageBox.Show(sqlex.Message, "Zduplikowany użytkownik.", MessageBoxButton.OK);
}
Perhaps the error to be returned is not type SqlException but type Exception.
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.
I have a problem with insert into statement..
cmd = new OleDbCommand("insert into FWINFOS (ID,Name,Gender,DateOfBirth,Race,WorkingPlace,PassportNO,DateOfExpire,Position,Photo) " +
"values('" + textBox5.Text + "','" + textBox1.Text + "','" + textBox2.Text +
"','" + dateTimePicker1.Value + "','" + textBox3.Text + "','" + textBox4.Text +
"','" + textBox6.Text + "','" + dateTimePicker2.Value + "',#Position,#Photo)", con);
conv_photo();
cmd.Parameters.AddWithValue("#Position", comboBox1.SelectedValue);
con.Open();
int n = cmd.ExecuteNonQuery();
//cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Inserted");
loaddata();
rno++;
}
else
MessageBox.Show("No Insert");
ERROR : Syntax Error INSERT INTO
Anyone can advise me? Please, Sorry for my bad English grammar.
Seem like you are missing out a parameter in your query, try using this
cmd.CommandText = "insert into Table1 (id,Position) values (#id,#Position)";
cmd.parameters.addwithvalue("#id", textBox1.Text);
cmd.parameters.addwithvalue("#Position", combobox1.selectedvalue);
new updated
-the position is the oleh db reserved words, try change to this query, put the cover to Position like below
cmd = new OleDbCommand("insert into FWINFOS (ID,Name,Gender,DateOfBirth,Race,WorkingPlace,PassportNO,DateOfExpire,[Position],Photo) " +
"values('" + textBox5.Text + "','" + textBox1.Text + "','" + textBox2.Text +
"','" + dateTimePicker1.Value + "','" + textBox3.Text + "','" + textBox4.Text +
"','" + textBox6.Text + "','" + dateTimePicker2.Value + "',#Position,#Photo)", con);
You have missed adding #Photo parameter in your code.
That is ok for testing purpose but you should never insert to database this way. This expose your system to a SQL Injection. You should use parametrized queries where possible. Something like
int result=0;
using (OleDbConnection myConnection = new OleDbConnection ("YourConnectionString"))
{
cmd = new OleDbCommand("insert into FWINFOS (ID,Name,Gender,DateOfBirth,Race,WorkingPlace,PassportNO,DateOfExpire,Position,Photo) values (#ID, #Gender, #DateOfBirth, #Race, #WorkingPlace, #PassportNO, #DateOfExpire, #Position, #Photo)", con);
conv_photo();
cmd.Parameters.AddWithValue("#ID", textBox5.Text);
// Specify all parameters like this
try
{
con.Open();
result = Convert.ToInt32(cmd.ExecuteNonQuery());
}
catch( OledbException ex)
{
// Log error
}
finally
{
if (con!=null) con.Close();
}
}
if(result > 0)
// Show success message
Also note that OleDb parameters are positional, means you have to
specify them in the exact order as in your query. OleDbParameter Class (MSDN)
There is no value for parameter #Photo, and if your photo field is not nullable or empty
in database structure then how you can add null value in that.So make your data field
nullable or pass value to parameter #Photo.I think it will solve your problem.
cmd = new OleDbCommand("insert into FWINFOS (ID,Name,Gender,DateOfBirth,Race,WorkingPlace,PassportNO,DateOfExpire,Position,Photo) " +
"values('" + textBox5.Text + "','" + textBox1.Text + "','" + textBox2.Text +
"','" + dateTimePicker1.Value + "','" + textBox3.Text + "','" + textBox4.Text +
"','" + textBox6.Text + "','" + dateTimePicker2.Value + "',#Position,#Photo)", con);
conv_photo();
cmd.Parameters.AddWithValue("#Position", comboBox1.SelectedValue);
cmd.Parameters.AddWithValue("#Photo", assignvalue);
con.Open();
int n = cmd.ExecuteNonQuery();
//cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Inserted");
loaddata();
rno++;
}
else
MessageBox.Show("No Insert");
I have a link button in my gridview at which I have some to insert value in table but it is not inserting but query data on debug mode when I tested on SQL Server it is inserted so whats the problem
protected void gvPO_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
c.GetConection();
SqlCommand cmd = new SqlCommand("delete from tmpMateIN", c.con);
cmd.ExecuteNonQuery();
DataTable dt;
int index = Convert.ToInt32(e.CommandArgument);
gvPO.SelectedIndex = index;
if (Convert.ToInt16(gvPO.SelectedIndex) < 0)
{
lblMsg.Text = "Please Select Code !";
return;
}
dt = oAccount.GetPO((int)Session["CompCode"], 79, Convert.ToInt16(((LinkButton)gvPO.Rows[gvPO.SelectedIndex].Cells[0].FindControl("lnkCode")).Text.ToString()));
for (int i = 0; i < dt.Rows.Count; i++)
{
String s6 = "insert into tmpMateIN(compcode ,msttype ,mstcode,mstdate ,mstchno ,mstblno ,mstbldt ,mstcust ,itdsrno , itditem ,itdquan ,itdrema ,itemname ,acctname ,ItmSize , unitname ,itemsize ,chno , chdt ,godown, packsize ,itdRate , itdDisc , itdAmou , mstInvNo , mstOrdNo,mstInvDt ,mstOrdDt ,mstrema , mstexcDes , msttaxDes ,msttaxper , mstfrghtDes , mstfrghtper , mstdeliDes ,mstpayDes , mstvaliDes, mstqno, mstqdt , itdthickness , itdlength ,itdwidth ,itdweight, itdtowt , acctaddr , custemail , mstpayMode , mstdepa,itdrefq,itdorgq)values(" + (int)Session["CompCode"] + ",79,'" + dt.Rows[i]["mstcode"] + "','" + dt.Rows[i]["mstdate"] + "'," + dt.Rows[i]["mstchno"] + ",'" + dt.Rows[i]["mstchno"] + "','" + dt.Rows[i]["mstdate"] + "','" + dt.Rows[i]["mstptcode"] + "','" + (i + 1) + "','" + dt.Rows[i]["itditem"] + "','" + dt.Rows[i]["itdquan"] + "','" + dt.Rows[i]["itdrema"] + "','" + dt.Rows[i]["itdnarr"] + "','" + dt.Rows[i]["AcctName"] + "','" + dt.Rows[i]["itdnarr"] + "','" + dt.Rows[i]["UnitName"] + "' ,'" + dt.Rows[i]["itdunit"] + "','','" + dt.Rows[i]["mstdate"] + "','',''," + dt.Rows[i]["itdRate"] + "," + dt.Rows[i]["itdamou"] + " ," + dt.Rows[i]["itdAmou"] + ",'" + dt.Rows[i]["mstInvNo"] + "','" + dt.Rows[i]["mstindno"] + "','" + dt.Rows[i]["mstdate"] + "','" + dt.Rows[i]["mstdate"] + "','" + dt.Rows[i]["mstrema"] + "','','','" + dt.Rows[i]["mstTaxPer"] + "','" + dt.Rows[i]["mstfrghtDes"] + "','" + dt.Rows[i]["mstfrghtper"] + "','" + dt.Rows[i]["mstdeliDes"] + "','" + dt.Rows[i]["mstpayDes"] + "','" + dt.Rows[i]["mstvaliDes"] + "','" + dt.Rows[i]["mstqno"] + "','" + dt.Rows[i]["mstpodate"] + "','" + dt.Rows[i]["itdthickness"] + "','" + dt.Rows[i]["itdsource"] + "','" + dt.Rows[i]["itddestin"] + "','" + dt.Rows[i]["itdweight"] + "','" + dt.Rows[i]["itdtowt"] + "','','" + dt.Rows[i]["acctaddr"] + "','" + dt.Rows[i]["mstpayMode"] + "','" + dt.Rows[i]["mstContactPerson"] + "','" + dt.Rows[i]["mstlotno"] + "','" + dt.Rows[i]["mstsection"] + "' )";
SqlCommand cmd1 = new SqlCommand(s6, c.con);
cmd1.ExecuteNonQuery();
}
c.CloseConnection();
Response.Redirect("Poreport.aspx");
}
}
You can run the SQL Server Profiler to see if the call is made to SQL Server for insertion at the time of execution of your program.
Suggestion: Why don't you use stored procedure instead of having this inline query this way:
var dr = dt.Rows[i];
SqlCommand cmd1 = new SqlCommand(s6, c.con);
cmd1.CommandType = System.Data.CommandType.StoredProcedure;
cmd1.CommandText = "tmpMateIN_Insert";
cmd1.Parameters.Add(new SqlParameter("#compcode", (int)Session["CompCode"]);
cmd1.Parameters.Add(new SqlParameter("#msttype", 79);
cmd1.Parameters.Add(new SqlParameter("#mstcode", dr["mstcode"]);
cmd1.Parameters.Add(new SqlParameter("#mstdate", dr["mstdate"]);
// ...
cmd1.ExecuteNonQuery();
ADDED:
OR if you really want to stick with an inline query then preferred approach is to use parameterized inline query as shown below:
String s6 = "insert into tmpMateIN(compcode, msttype, mstcode, mstdate, ..." +
"values(#compcode, #msttype, #mstcode, #mstdate, ...";
cmd1.Parameters.Add(new SqlParameter("#compcode", (int)Session["CompCode"]);
cmd1.Parameters.Add(new SqlParameter("#msttype", 79);
cmd1.Parameters.Add(new SqlParameter("#mstcode", dr["mstcode"]);
cmd1.Parameters.Add(new SqlParameter("#mstdate", dr["mstdate"]);
// ...
cmd1.ExecuteNonQuery();