Error parsing query from C# program to SQL Server CE - c#

I need to update the details in a certain row of my SQL Server CE database as the user wants requires to. But I get an error
There was an error parsing the query.[Token line number=1,Token line offset=31,Token in error=Name]
My query is:
"Update MembersTable set First Name='" + txtFirstName.Text +
"', Surname='" + txtSurname.Text +
"', Middle Name='" + txtMiddleName.Text +
"',Home Address='" + txtAddress.Text +
"',Date Of Birth='" + dtpDOB.Text +
"',Home Phone No='" + txtHomePhone.Text +
"',Mobile No='" + txtMobilePhone.Text +
"',Email='" + txtEmail.Text +
"',Profession='" + txtProfession.Text +
"',Cell Leaders Name='" + txtCellLeader.Text +
"' Where ID='" + DC.ID + "'";"
What am I doing wrong??

It appears like your column names contain spaces.
To deal with this, you'd want to enclose the column name with square brackets [ ]
"Update MembersTable set [First Name]='" + txtFirstName.Text + "',Surname='" + txtSurname.Text + "',[Middle Name]='" // ...

Related

I'm working on windows form with access database. i want to get the count of product between two dates. This following query is getting error

select DOA, count(srno)
from purchase
where pname='" + dataGridView1.Rows[i].Cells[0].Value.ToString() + "'
AND company='" + cmb_cmp.Text + "' AND DOA between '" + date + "' and '" + dat + "';
While you read up on parameters:
AND company='" + cmb_cmp.Text + "' AND DOA between #" + date.ToString("yyyy'/'MM'/'dd") + "# and #" + dat.ToString("yyyy'/'MM'/'dd") + "#";

C# windowsform - Getting Syntax Error at Insert into statement

I'm trying to remake my system and my older system is 100% working, but when I changed something (I added a lot of columns in ms access database) I did the correct format in inserting data of each textboxes but it still says "error in insert into statement".
This is my code. Please take your time reading the query for that is only the error I got. I double checked the spelling or capitalization on each field from database as well as here.
try
{
connection.Open(); //open connection
OleDbCommand command = new OleDbCommand(); // command object , we can execute to validate our database
command.Connection = connection; // make a connection for the command
command.CommandText = " insert into StudentsRecord([StudentID],Name,Section,Semester,MathPrelim,MathMidterm,MathFinals,MathAverage,MathFinalGrade,EnglishPrelim,EnglishMidterm,EnglishFinals,EnglishAverage,EnglishFinalGrade,SciencePrelim,ScienceMidterm,ScienceFinals,ScienceAverage,ScienceFinalGrade,StatisticsPrelim,StatisticsMidterm,StatisticsFinals,StatisticsAverage,StatisticsFinalGrade,ReadandWritePrelim,ReadandWriteMidterm,ReadandWriteFinals,ReadandWriteAverage,ReadandWriteFinalGrade) values ('" + txtStudentID.Text + "' , '" + txtName.Text + "' , '" + txtSection.Text + "' , '" + cmbSemester.SelectedItem + "', '" + txtMathp.Text + "' , '" + txtMathm.Text + "' , '" + txtMathf.Text + "' , '" + txtMatha.Text + "' , '" + txtMathFG.Text + "' , '" + txtEnglishp.Text + "' , '" + txtEnglishm.Text + "', '" + txtEnglishf.Text + "','" + txtEnglisha.Text + "','" + txtEnglishFG.Text + "','" + txtMathFG.Text + "','" + txtSciencep.Text + "','" +txtSciencem.Text+ "','" + txtSciencef.Text + "','" + txtSciencea.Text + "','" + txtScienceFG.Text + "','" + txtStatisticsp.Text + "','" + txtStatisticsm.Text + "','" + txtStatisticsf.Text + "','" + txtStatisticsa.Text + "','" + txtStatisticsFG.Text + "','" + txtReadandWritep.Text + "','" + txtReadandWritem.Text + "','" + txtReadandWritef.Text + "','" + txtReadandWritea.Text + "','" + txtReadandWriteFG.Text + "')";
/* this is a string or a query used to execute. asterisk is used
to give you all column data from your database ,declaration of query */
command.ExecuteNonQuery(); // this is used to inserting data , updating or deleting data , this command will execute the above query
MessageBox.Show(" Saved! ");
}
catch (Exception a)
{
MessageBox.Show(" Error " + a.Message);
}
connection.Close();
I see in the first part you have 29 fields, but the inserted fields are 30...
In addition, you should use parameterized queries to avoid sql injection.
You need to debug codes and paste your CommandText to SSMS(SQL Sever Management Studio) to figure out errors.
Other suggestions:
command.CommandText = string.format("insert into StudentsRecord(..) VALUES(#...)); sql params to avoid sql injection
using(SqlConnection conn = ...)
Already solved the problem just now by putting [ ] on each field. which will be something like this:
insert into StudentsRecord(
[StudentID],[Name],[Section],[Semester],
[MathPrelim],[MathMidterm],[MathFinals]
) values ('"++"'..) ... etc.
Thanks everyone who tried to help me, have a good day!

Error with SQL syntax (in Windows form , C#)

I'm trying to insert some data into my table and that's how I try to do it
INSERT INTO OrdersDetail
Values (" + OrderId.Text + ", (SELECT IdProduct FROM Products WHERE ProductName = '" + listBox1.Text + "'), '" + TypeOfProductComboBox.Text + "', '" + OrderQuantity.TextAlign + "', '" + TotalCost.Text + "'");
and I'm geting error I think my syntax is wrong, I'm use query in query to get the product id.
The columns are :
OrderId (int)
ProductId(int)
ProductName(Nvarchar)
OrderQuantity(Nvarchar)
TotalCost(NvarChar)
Thanks
You set your inside SELECT under '. Should be:
var query = "INSERT INTO OrdersDetail Values (" + OrderId.Text + ", (SELECT IdProduct FROM Products WHERE ProductName = '"+ listBox1.Text + "'), '" + TypeOfProductComboBox.Text + "', '" + OrderQuantity.TextAlign + "', '" + TotalCost.Text + "')");
If for example TotalCost.Text is a numeric data type in SQL, use
"..." + OrderQuantity.TextAlign + "', " + Convert.ToDouble(TotalCost.Text) + ")";
As p.s.w.g stated: This is open for SQL injection. Replace it with a parameterized version!
I think the problem is with the first Line and your inside Select.
This should work
INSERT INTO OrdersDetail
Values ('" + OrderId.Text + "',(SELECT IdProduct FROM Products WHERE ProductName ='"+ listBox1.Text + "')," + TypeOfProductComboBox.Text + "','" + OrderQuantity.TextAlign + "','" + TotalCost.Text + "'");
The problem is that you are missing the last bracket, the query should finish with "')" instead of "'" . The initial code started with opening bracket and that is why you didn't get compile errors.
But you should not create such sql queries, use Parameters to avoid SQL injection attacks. You code is vulnerable to them.

DateTime value from Oracle to MySql database

I have a question, how to parse datetime value from Oracle to MySQL database.
I wrote this to extract a datetime from Oracle:
SELECT TO_CHAR(p1.creation_date,'DD.MM.RRRR HH24:mi:ss') AS dat_pot
FROM TABLE
then I put the result into data set, then I extract the value of date from dataset like this:
string lDat_otp = null;
if (rw_mat["dat_otp"].ToString().Length <= 0)
{
lDat_otp = "0";
}
else
{
lDat_otp = "convert(datetime,'" + rw_mat["dat_otp"] + "',4)";
}
Then I use lDat_otp in INSERT statement with some other values like this:
myQuery = " INSERT INTO ordersstavke (BrDok, " +
" SifParFil, SifParIsp, DatPriOtpr, SifPodKla, Masa, Paketa) " +
" VALUES ('" + rw_mat["brdok"] + "', '" +
rw_mat["sifskl_kor"] + "','" +
rw_mat["partner"] + "'," +
lDat_otp + ",'" +
rw_det["ibrmat"] + "', '" +
rw_det["izlaz_tez"] + "', '" +
rw_det["izlaz_kol"] + "')";
But there is an error on execute and it goes:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '26.01.2012 13:48:41',4)','100654', '0', '10')' at line 1
So help!!!
You can parse the datetime field into a DateTime struct and then create an insert into query with parameters and pass the date as parameter :
DateTime time = //Some value ...
String myQuery = " INSERT INTO ordersstavke (BrDok, " +
" SifParFil, SifParIsp, DatPriOtpr, SifPodKla, Masa, Paketa) " +
" VALUES ('" + rw_mat["brdok"] + "', '" +
rw_mat["sifskl_kor"] + "','" +
rw_mat["partner"] + "'," +
"?date ,'" +
rw_det["ibrmat"] + "', '" +
rw_det["izlaz_tez"] + "', '" +
rw_det["izlaz_kol"] + "')";
MysqlCommand command = new MysqlCommand(query, connection);
command.Parameters.AddWithValue("?date", time);
Doing this you should not have problems with date formatting.
I strongly suggest to use parameters instead of string concatenation even for the others parameters of the query ...

Data type mismatch in criteria expression

I have a windows service which inserts data into some tables. It does so fine when in debug mode, but when I install it says "Data type mismatch in criteria expression." for every insert.
query = "INSERT INTO printers (" +
"hostname," +
"ip_address," +
"model," +
"picture_id," +
"connect_type," +
"status," +
"product_number," +
"Floor_ID," +
"print_corner," +
"serial_number," +
"printer_features" +
") VALUES ('" +
exp.Devices[i].HostName.ToString() + "', '" +
exp.Devices[i].IpAddress.ToString() + "', '" +
exp.Devices[i].Model.ToString() + "', '" +
exp.Devices[i].PictureId.ToString() + "', '" +
exp.Devices[i].ConnectType.ToString() + "', '" +
exp.Devices[i].Status.ToString() + "', '" +
exp.Devices[i].ProductNumber.ToString() + "', '" +
exp.Devices[i].Floor.ToString() + "', '" +
exp.Devices[i].PrintCorner.ToString() + "', '" +
exp.Devices[i].SerialNumber.ToString() + "', '" +
exp.Devices[i].PrinterFeatures.ToString() +
"')";
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + confParams.MpaSearchDatabase;
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbCommand myCommand = new OleDbCommand(query);
myCommand.Connection = conn;
conn.Open();
myCommand.ExecuteNonQuery();
conn.Close();
insertedPrintersCount = insertedPrintersCount + 1;
Utils.Logger.Info("Device inserted: " + exp.Devices[i].HostName);
help!
The data type mismatch error indicates the query is expecting data of one type but you're providing another. This query expression is passing every value as a string literal but several columns indicate they are likely a numerical value. ProductNumber and SerialNumber for example.
In order to pass the values correctly (and prevent easy injection attacks) you'll want to use the OleDbCommand class to build up the call with values of the correct type. Then let the underlying infrastructure translate it to the appropriate values.

Categories

Resources