sql insert statement using sql transaction not working - c#

SqlConnection con = new SqlConnection(GlobalData.GetConnectionString());
string queryDepartment = null;
if (rbtnYes.Checked == true)
{
if (rbtnMale.Checked == true)
{
queryDepartment =
#"BEGIN TRY
BEGIN TRAN
insert into UserDetails
values('" + Convert.ToInt32(txtID.Text) + "','" + txtFullName.Text + "','" + txtPassword.Text + "','" + txtUserName.Text + "','" + cbDepartment.SelectedValue.ToString() + "','" + txtContactAddress.Text + "','" + Convert.ToInt64(txtContactNumber.Text.ToString()) + "','" + txtContactEmail.Text + "',CAST(GETDATE() AS DATE),'" + rbtnYes.Text + "',null,'" + rbtnMale.Text + "','" + Convert.ToInt64(txtSalary.Text.ToString()) + #"');
insert into Users
values('" + GlobalData.UsersID_AddUsers + "','" + GlobalData.RoleID_AddUsers + "','" + txtUserName.Text + "','" + Convert.ToInt32(txtID.Text) + #"');
COMMIT TRAN
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber,ERROR_SEVERITY() AS ErrorSeverity,ERROR_STATE() AS ErrorState,ERROR_PROCEDURE() AS ErrorProcedure,ERROR_LINE() AS ErrorLine,ERROR_MESSAGE() AS ErrorMessage
IF ##TRANCOUNT > 0
ROLLBACK TRANSACTION
END CATCH";
}
}
i am trying to insert records using sql transaction into two table from c# code but it is not working.
while the same statement i am inserting in sql table using sql management software its working.

Your SQL starts with a BEGIN but has no matching END. You do not need the BEGIN - remove it.

Since you said there are no errors come out then i guess this is the problems, your condition doesnt match, would you mind to put a debugged point to check is your condition matches to call your insert function?
if (rbtnYes.Checked == true)
if (rbtnMale.Checked == true)

Thank You Every One I have Solved My Problem My Own.........
the problem is the
GlobalData.RoleID_AddUsers is 0..
but because of sql try catch its not showing me the error....or catching the exception....
but when i removed the sql try catch...then its start throwing the exception saying that foreign key violation....and bla bla........and i adjust the code as per the requirement....
and problem solved......:)

Related

Whenever I Insert Data in Database It Saves an Extra Row in Database

layout and db
if (!(string.IsNullOrEmpty(b.ToString())))
{
string connection = "server=127.0.0.1; database=accounts;user=root; password='';";
MySqlConnection conn = new MySqlConnection(connection);
conn.Open();
string SQL = "INSERT INTO payment_voucher (voucher_no, paid_to, date, account_cr, account_dr, description, student_emp_id, amount, total ) values ('" + label8.Text.ToString() + "','" + textBox1.Text + "', '" + dateTimePicker1.Value + "','" + a + "','" + b + "', '" + richTextBox1.Text + "', '" + textBox3.Text + "', '" + textBox4.Text + "', '" + label11.Text.ToString() + "');";
MySqlCommand command = new MySqlCommand(SQL, conn);
command.ExecuteNonQuery();
conn.Close();
}
i dont know why it is happening. front end is in C#.
That statement will not insert two rows.
You have a few things to check here:
Check if that code is being called twice
Check if there is other similar code that is also being called
Make sure there are no triggers on the table that do an additional insert
Make sure you don't have some weird Try/Catch/Fail logic that causes that entire thing to be run again
And most importantly:
Run a SQL Profiler trace to see exactly what is being sent to the database
Query the table when you've checked those with a raw SELECT query in Enterprise Manager and make sure there is one row.
That code above would not duplicate rows unless called twice.

I want to insert multiple rows into SQL Server database, but get syntax errors

I want to insert multiple pieces of data into a SQL Server database as shown below, but when I run this code, I get a syntax error
Incorrect syntax near the keyword 'union'.
Incorrect syntax near ''.
Incorrect syntax near ''.
Incorrect syntax near ''.
Code:
SqlCommand cmd2 = new SqlCommand("INSERT INTO [rampDB].[dbo].[Answers]([AssessmentID],[questionID],[result],[comment]) SELECT('"
+ assessmentid + "1.1a" + RadioButtonList1.SelectedItem.Value.ToString() + TextBox1.Text + "'union'"
+ "'SELECT'" + assessmentid + "1.1b" + RadioButtonList2.SelectedItem.Value.ToString() + TextBox2.Text + "'union'"
+ "'SELECT'" + assessmentid + "1.1c" + RadioButtonList3.SelectedItem.Value.ToString() + TextBox3.Text + "'union'"
+ "'SELECT'" + assessmentid + "1.1d" + RadioButtonList4.SelectedItem.Value.ToString() + TextBox4.Text + "'union'"
+ "'SELECT'" + assessmentid + "1.1e" + RadioButtonList5.SelectedItem.Value.ToString() + TextBox5.Text
+ "')", sqlConn);
Multiple-insert syntax for SQL Server is possible with only INSERT, like so:
INSERT INTO rampDB.dbo.Answers (
assessmentID, QuestionId, Result, Comment
) VALUES
( #r1v1, #r1v2, #r1v3, #r1v4 ),
( #r2v1, #r2v2, #r2v3, #r2v4 ),
( #r3v1, #r3v2, #r3v3, #r3v4 )
That said, the best way is to use a single INSERT with parameters, which is then executed for each row.
Relpace "'union'" with this--> "union"

uploading xml file to sql, turn off primary key in command

I've searched google and youtube and here of course and i can't find the answer. I need to turn the identity insert On and OFF but don't know how to do that in the sql command of the ADO.Net project. I'm sure it must be extremely easy for you highly experienced people.
additional information I'm using c#, visual studio and sql server, i don't know if that helps narrow the problem down?
here is sql command i tried in the ado.net project.
sql = "SET IDENTITY_INSERT HomeCareVisit ON insert into HomeCareVisit values("
+ VisitRefNo + ",'" + PatientNo + "','" + ScheduledDateTime + "','"
+ TreatmentInstructions + "','" + MedicalStaffID + "','" + Priority + "','"
+ ActualVisitDateTime + "','" + TreatmentProvided + "','" + Prescription
+ "','" + AdvisoryNotes + "'," + (FurtherVisitRequired ? "1" : "0") + " );";
and it gave the error
Violation of PRIMARY KEY constraint 'PK_VisitRefNo'. Cannot insert duplicate key in object 'dbo.HomeCareVisit'.
The statement has been terminated.
here is the code shows what data type the column are
VisitRefNo = ds.Tables[0].Rows[i].ItemArray[0].ToString();
PatientNo = Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[1]);
ScheduledDateTime = Convert.ToDateTime(ds.Tables[0].Rows[i].ItemArray[2]);
TreatmentInstructions = ds.Tables[0].Rows[i].ItemArray[3].ToString();
MedicalStaffID = Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[4]);
Priority = ds.Tables[0].Rows[i].ItemArray[5].ToString();
ActualVisitDateTime = Convert.ToDateTime(ds.Tables[0].Rows[i].ItemArray[6]);
TreatmentProvided = ds.Tables[0].Rows[i].ItemArray[7].ToString();
Prescription = ds.Tables[0].Rows[i].ItemArray[8].ToString();
AdvisoryNotes = ds.Tables[0].Rows[i].ItemArray[9].ToString();
FurtherVisitRequired = Convert.ToBoolean(ds.Tables[0].Rows[i].ItemArray[10]);
This is the command to do it
SET IDENTITY_INSERT YourTable ON
Try this:
sql = "SET IDENTITY_INSERT HomeCareVisit ON insert into HomeCareVisit(column_names) values("
+ VisitRefNo + ",'" + PatientNo + "','" + ScheduledDateTime + "','"
+ TreatmentInstructions + "','" + MedicalStaffID + "','" + Priority + "','"
+ ActualVisitDateTime + "','" + TreatmentProvided + "','" + Prescription
+ "','" + AdvisoryNotes + "'," + FurtherVisitRequired + " );";
where column_names is list of table columns in order in which you insert.
I think you pass string in place where table doesn't expect this, like TreatmentProvided column (by name, i assume that you pass True/False, but not as string).

SQlite insert not working

I'm writing a C# database winform app and I have a problem executing this query. It throws me this error:
SQLite error
near "SELECT": syntax error
Can someone help me please? Thanks for any answer or suggestion.
"INSERT into subor(idsubor, idpodfk, pnazovfk, datumpravop, podiel, podield, cislozLV,
datumzaradenia, idmajetok)
values (null, " + comboBox1.SelectedValue.ToString() + ",
'" + comboBox2.SelectedValue.ToString() + "',
'" + dateTimePicker1.Value.ToString("d. M. yyyy") + "',
'" + textBox2.Text + "',
" + podield.ToString("0.0000", System.Globalization.CultureInfo.InvariantCulture) + ",
'" + textBox4.Text + "',
'" + dateTimePicker2.Value.ToString("d. M. yyyy") + "',
SELECT IFNULL(a, '0') AS idmajetok
FROM (SELECT MAX(idmajetok) + 1 AS a FROM subor))";
Your C# string/SQLite SQL mixture still seems somewhat confusing, but one possible issue that I'm seeing is as follows:
You are using a SELECT statement to indicate one of the values in your VALUES list. As you can see in the syntax diagram, that SELECT statement has to be enclosed in parenthesis.
i suspect some SQL syntax Problem, and i made some changes to your select statement.
Please try out:
string sqlInsert = "INSERT into subor(idsubor, idpodfk, pnazovfk, datumpravop,
podiel,podield, cislozLV, datumzaradenia, idmajetok) values (null, '" +
comboBox1.SelectedValue.ToString() + "','" + comboBox2.SelectedValue.ToString() + "','" +
dateTimePicker1.Value.ToString("d.M.yyyy") + "','" + textBox2.Text + "','" +
podield.ToString("0.0000", System.Globalization.CultureInfo.InvariantCulture) + ",'" +
textBox4.Text + "','" + dateTimePicker2.Value.ToString("d.M.yyyy") + "','" + "SELECT
IFNULL(a, '0') AS idmajetok FROM (SELECT MAX(idmajetok) + 1 AS a FROM subor) )');";}

syntax error in query

I am new to programming and is developing a new desktop database applcation in Access, I am trying to insert data into a table. I had two datetime picker and I read the value from it as
jobcodedatabean.PaperRecievedate1 = dtpjobcodedate.Value.Date;
jobcodedatabean.Shipmenentdate = dtpshipmentdate.Value.Date;
and I had passed the databean to a function
public void addaction(JobCodeDataBean jobcodedatabean)
{
MessageBox.Show(jobcodedatabean.Shipmenentdate.ToString());
try
{
OleDbConnection oleDbConnection1 = new System.Data.OleDb.OleDbConnection(connString);
oleDbConnection1.Open();
OleDbCommand oleDbCommand1 = new System.Data.OleDb.OleDbCommand("INSERT INTO jobcodemastertable (jobcode ,customercode,totaltrip,shipmentdate,fromPlace, destination,description ,packagetype ,noofpackage ,contactperson ,jobecodedate ) Values ('" + jobcodedatabean.Jobcode + "', '" + jobcodedatabean.Customercode + "' ," + jobcodedatabean.Totaltrip + "," + jobcodedatabean.Shipmenentdate + " ,'" + jobcodedatabean.Fromplace + "','" + jobcodedatabean.Destination + "','" + jobcodedatabean.Description + "','" + jobcodedatabean.Typeofpackage + "','" + jobcodedatabean.Noofpackages + "','" + jobcodedatabean.Contactperson + "'," + jobcodedatabean.PaperRecievedate1 + ") ", oleDbConnection1);
oleDbCommand1.CommandType = CommandType.Text;
oleDbCommand1.ExecuteNonQuery();
oleDbConnection1.Close();
}
catch (Exception)
{
MessageBox.Show(e);
}
but i am getting the exception at the query
Syntax error (missing operator) in query expression '2/16/2012 12:00:00 AM'.
In access the date fields are in short date format
Please somebody help to sort out my mistake
Incorrect quotations. To avoid these kinds of mistakes, use ordered parameters:
var myCommand = new OleDbCommand(
"INSERT INTO MyTable(someDateField, someTextField, someNumberField) VALUES (?, ?, ?)"
);
myCommand.Parameters.Add(DateTime.Now);
myCommand.Parameters.Add("Some text");
myCommand.Parameters.Add(123);
Using parameters also helps protect against SQL injection attacks. In your example, if one of the strings contained an apostrophe, it would fail unless you correctly converted it to two apostrophes. With parameters these are escaped correctly automatically.
You forgot to enclose dates in quotes:
... ",'" + jobcodedatabean.Shipmenentdate + "' ,'" ...
... "','" + jobcodedatabean.PaperRecievedate1 + "') " ...
Note single quotes around both dates.

Categories