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).
Related
I have a simple user interface for an inventory database. The operation will be insert into, edit existing, view data grid, etc....There are a total of 4 fields for the inventory. The insert statement I am using works but if one of the entries does not have a value then it shows an error when trying to insert.
" Data type mismatch in criteria expression "
command.CommandText = "insert into Inventory(SerialNumber,PartNumber,ROnumber,Location)
values ('" + txtPart.Text + "','" + txtSerial.Text + "','" +
txtRO.Text + "','" + txtLocation.Text + "')";
I assume it is because the code needs a value for each field so how do I get around this issue?.
Actually when you trying to use this query you have said the First Parameter is SerialNumber and then PartNumber and when you are passing its reverse.
command.CommandText = "insert into Inventory(SerialNumber,PartNumber,ROnumber,Location)
values ('" + txtPart.Text + "','" +
txtSerial.Text + "','" +
txtRO.Text + "','" +
txtLocation.Text + "')";
Due to this reason the fields you are entering have different size May be part number is bigger in size instead of SerialNumber or vice versa. So you should change it to
command.CommandText = "insert into Inventory(SerialNumber,PartNumber,ROnumber,Location)
values ('" + txtSerial.Text + "','" +
txtPart.Text + "','" +
txtRO.Text + "','" +
txtLocation.Text + "')";
I have tried to insert data in MS access database but data is not added in database and error not given.
private void btnsubmit_Click(object sender, EventArgs e)
{
int row = dataGridView1.RowCount;
for (int i = 0; i < row - 1; i++)
{
String str = "INSERT INTO JDS_Data(job_no,order_no,Revision,DesignSpec,Engine_Type,Record_date,LE_IN_Designer,CPH_Designer,Exp_Del_Week,Action_code,Rev_Description,Ref_pattern,Name_of_mock_up,EPC_Drawing,Turbocharger_no_Type,Engine_Specific_Requirement,Draft_sketch_with_details,Air_cooler_type,Description_of_Job,SF_No,Standard,Prority_Sequence,Remark,Part_family,Modified_Date,User) values('" + txtjobno.Text + "','" + txtorderno.Text + "','" + txtrevison.Text + "','" + txtds.Text + "','" + txtenginetype.Text + "','" + dateTimePicker1.Text + "','" + txtleindesigner.Text + "','" + txtcphdesigner.Text + "','" + txtexpweek.Text + "','" + txtactioncode.Text + "','" + txtrevdescription.Text + "','" + txtrefpatern.Text + "','" + txtmockup.Text + "','" + txtepcdwg.Text + "','" + txtturbono.Text + "','" + txtenginereq.Text + "','" + txtdraft.Text + "','" + txtaircolertype.Text + "','" + txtdespjob.Text + "','" + dataGridView1.Rows[i].Cells[0].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[1].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[2].Value.ToString() + "','" + txtremark.Text + "','" + dataGridView1.Rows[i].Cells[3].Value.ToString() + "','" + DateTime.Today + "','" + mdlconnection.user_name + "')";
int dd = mdlconnection.excuteQuery(str);
MessageBox.Show(str);
//if (dd > 0)
{
MessageBox.Show("Data Saved Successfully..!!!");
}
}
}
Hey your query have Syntax error use below line
String str = "INSERT INTO JOB_Quality_Rating(Team,JOB_Type,Designer_Name,AUR_NO,Task_No,Sub_Function_no,Severity_Level,Checkpoints,Points_Deducted,Total_Points,Submitted_By,Submitted_Date) values('" + comboBox1.SelectedItem + "','"+comboBox7.SelectedItem+"','" + comboBox3.SelectedItem + "','" + comboBox6.SelectedItem + "','" + cmbtaskno.SelectedItem + "','" + comboBox2.SelectedItem + "','" + dataGridView1.Rows[i].Cells[0].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[1].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[2].Value.ToString() + "','" + txtTotal.Text + "','" + mdlconnection.user_name + "','" + dateTimePicker1.Text + "')";
Instead of
String str = "INSERT INTO JOB_Quality_Rating(Team,JOB_Type,Designer_Name,AUR_NO,Task_No,Sub_Function_no,Severity_Level,Checkpoints,Points_Deducted,Total_Points,Submitted_By,Submitted_Date) values('" + comboBox1.SelectedItem + "',,'"+comboBox7.SelectedItem+"','" + comboBox3.SelectedItem + "','" + comboBox6.SelectedItem + "','" + cmbtaskno.SelectedItem + "','" + comboBox2.SelectedItem + "','" + dataGridView1.Rows[i].Cells[0].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[1].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[2].Value.ToString() + "','" + txtTotal.Text + "','" + mdlconnection.user_name + "','" + dateTimePicker1.Text + "')";
Hope it helps.
Probably your syntax is incorrect. Constructing query with string concatenation is always a bad idea. Use parametrized query string with built-in parameter values handling via OdbcCommand.Parameters.Add(...).
cyberj0g is right, your syntax is incorrect. Particularly, you've got a value missing in your values list at around here: ...comboBox1.SelectedItem + "',,'"+comboBox7.SelectedItem.... You can't pass an empty value this way. Either pass NULL here or remove the respective field form the field list clause: ...Team,Designer_Name... (and the extra comma too, or course).
You can try the following -
- Try executing the query string (what is formed in str variable) manually in access to make sure there are no errors in he syntax and it executes there successfully
- Wrap the execution statement in try..catch block to get error detail
- Make sure the connection is pointing to the correct database instance
foreach (DataGridViewRow ro in dgvOrderGroup.Rows)
{ datbas.RunNonQuery("INSERT INTO [RestOrders] VALUES(" + ro.Cells[0].Value + ",'"
+ ro.Cells[1].Value + "'," + ro.Cells[2].Value + ",'"
+ ro.Cells[3].Value + "','" + ro.Cells[4].Value
+ "','" + ro.Cells[5].Value + "','" + ro.Cells[6].Value + "')"); }
I suspect your ro.Cells[0].Value and ro.Cells[2].Value (assume they are character typed columns) don't have single quotes in your query.
Try it like;
VALUES('" + ro.Cells[0].Value + "','"... + "','" + ro.Cells[2].Value + "','"
Would be better if we know your values and column types of course..
I want to get id after I insert a row of data into a table but I get an error:
System.InvalidCastException: Specified cast is not valid.
This is my code
SqlCommand cmd_insert = new SqlCommand("insert into ITM_OrderItem (ITM_Code, ITM_Desc, ORCAT_Desc, ORSCT_Desc, ARCBG_Abbrev, ARCSG_Desc, ARCSC_Code, ARCIM_DerivedFeeItem, OPD_Price, IPD_Price, Tou_Price, App_Status, SITES, CSSUSR_RowId, CSSUSR_DepId, CSSUSR_PosId , CDate, MDate) values('"
+ dt.Rows[i]["EARCIM_Code"].ToString() + "','"
+ dt.Rows[i]["EARCIM_Desc"].ToString() + "','"
+ dt.Rows[i]["EORCAT_Desc"].ToString() + "','"
+ dt.Rows[i]["EARCIC_Desc"].ToString() + "','"
+ dt.Rows[i]["EARCBG_Abbrev"].ToString() + "','"
+ dt.Rows[i]["EARCSG_Desc"].ToString() + "','"
+ dt.Rows[i]["EARCSC_Desc"].ToString() + "','"
+ dt.Rows[i]["EARCIM_DerivedFeeItem"].ToString() + "','"
+ dt.Rows[i]["OPD"].ToString() + "','"
+ dt.Rows[i]["IPD"].ToString() + "','"
+ dt.Rows[i]["Tourist"].ToString() + "','"
+ status_app + "','"
+ usr_site + "','"
+ usrID + "','"
+ Dep_RowId + "','"
+ Pos_RowId + "','"
+ Cdate + "','"
+ Cdate + "') select SCOPE_IDENTITY()", conEMR);
// error on this line
insert_RowId = (Int32)cmd_insert.ExecuteScalar();
Thank you a lot.
It looks as if the identity column in your table ITM_OrderItem does not use int as data type, What I can guess is that it is a bigint data type and if that is the case you should change the line in your code to:
insert_RowId = (Int64)cmd_insert.ExecuteScalar();
Also make sure that you change the datatype of variable 'insert_RowId' to Int64 in your C# code declaration.
Here is my code
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
sqlCmd.CommandText = "INSERT INTO ChheckOut(rakmsheek,tare5sheek,esmsa7bsheek,mablgh,hesab,esmel7sab,mla7zat,rakmkeed,tare5,rakmel3mel,segldareby,most5dm,rakm7araka,madfo3nakdan,madfo3bshikat,magmo3shikat,mgmo3nakdanwshikat,khasmelmosder,mablgh7esab,esmel3mel,addresso) VALUES ('"
+ dataGridView1.Rows[i].Cells["Column1"].Value + "', '"
+ dataGridView1.Rows[i].Cells["Column2"].Value + "','"
+ dataGridView1.Rows[i].Cells["Column3"].Value + "', '"
+ dataGridView1.Rows[i].Cells["Column4"].Value + "',' "
+ dataGridView1.Rows[i].Cells["Column5"].Value + "',' "
+ dataGridView1.Rows[i].Cells["Column6"].Value + "', '"
+ dataGridView1.Rows[i].Cells["Column7"].Value + "','"
+ maskedTextBox1.Text + "','" + maskedTextBox19.Text + "','"
+ maskedTextBox3.Text + "','" + maskedTextBox4.Text + "','"
+ maskedTextBox12.Text + "','" + maskedTextBox13.Text + "','"
+ maskedTextBox6.Text + "','" + maskedTextBox10.Text + "','"
+ maskedTextBox7.Text + "','" + maskedTextBox9.Text + "','"
+ maskedTextBox8.Text + "','" + maskedTextBox11.Text + "','"
+ textBox1.Text + "','" + textBox2.Text + "');";
sqlCmd.ExecuteNonQuery();
db.SaveChanges();
}
Not full rows insert into the database I don't know why. And its random, not the same data left every time :(
What does your table schema look like? Also, what is some sample data you are trying to insert?
If the insert is succeeding, but the data stored isn't what you were expecting, it's probably not inserting null into not null. If the only fields not showing up are datetime data types, that might be a huge clue. Make sure you are actually trying to insert the correct datatypes.