SQlite insert not working - c#

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) )');";}

Related

Insert data from DataGridView to Access Database in C# (however it works ,syntax error in insert into statement appear)

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..

error when i insert data and select last id

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.

Why some date Ignored when insert from DataGridView into database?

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.

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).

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