C# windowsform - Getting Syntax Error at Insert into statement - c#

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!

Related

Conversion to date time from char string failed on Insert but works on Update

i'm currently getting the following error when inserting a date into a database, but it works fine when amending the date via a update:
Conversion failed when converting date and/or time from character string
The code I have (Very crappy i know, learning on the fly...):
update - working
SqlCommand update = new SqlCommand("Update bookings set Guests = '" +
drptxtGuests.Text + "'," + "CheckInDate = '" +
BasicDatePicker1.SelectedDate + "'," + "CheckOutDate = '" +
BasicDatePicker2.SelectedDate + "'," + "RoomType = '" +
drptxtRoomType.Text + "'," + "Price = '" + txtBookingPrice.Text +
"' where BookingNumber = '" + txtBookingNumber.Text + "'" , con);
update.ExecuteNonQuery();
con.Close();
insert - error
SqlCommand insert = new SqlCommand("Insert into bookings(BookingNumber, MemberID, " +
"CheckInDate, CheckOutDate, Guests, RoomType, Price) values('" +
txtBookingNumber.Text + "','" + Session["id"] + "','" +
BasicDatePicker1.SelectedDate + "','" + BasicDatePicker2.SelectedDate +
"','" + drptxtGuests.Text + "','" + drptxtRoomType.Text + "','" +
txtBookingPrice.Text + "')", con);
insert.ExecuteNonQuery();
con.Close();
i wouldn't be surprised if it was something very basic, obvious and stupid but please bear with me. :)
edit: Im also certain that the problem is with the datepickers, i just dont understand why it works for updating and not inserting?

SQL Command Error

here is the story :
Im trying to insert some data form the form to my data base but some thing wrong with the syntax "Vs Say so" but i can't find the mistake and some one help ?
MySqlConnection conn = new MySqlConnection("Server=localhost;Database=ltdb;UID=root;Password=1234;port=3306");
try
{
string command = "(INSERT INTO invoice companyName,rate,svatNo,tinNo,line1,line2,city)VALUES('" + this.txtname.Text + "','" + this.txtrate.Text + "','" + this.txtsvatno.Text + "','" + this.txttinno.Text + "','" + txtadline1.Text + "','" + txtadline2.Text + "','" + txtcity.Text + "');";
conn.Open();
MySqlCommand cmd = new MySqlCommand(command, conn);
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Saved !");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
INSERT INTO invoice companyName, ... missing opening brace, correct is
INSERT INTO invoice(column1, column2, ...) VALUES (#Columns1, #columns2, ...)
Coming to point 2: you're open for sql-injection. Use parameterized queries.
Change your
string command = "(INSERT INTO invoice companyName,rate,svatNo,tinNo,line1,line2,city)VALUES('" + this.txtname.Text + "','" + this.txtrate.Text + "','" + this.txtsvatno.Text + "','" + this.txttinno.Text + "','" + txtadline1.Text + "','" + txtadline2.Text + "','" + txtcity.Text + "');";
To
string command = "INSERT INTO invoice (companyName,rate,svatNo,tinNo,line1,line2,city) VALUES (#name,#rate,#vatno,#tinno,#adline1,#adline2,#city)";
command.Parameters.AddWithValue("name",txtname.Text);
command.Parameters.AddWithValue("rate",txtrate.Text);
....
*Edit: For more info, google "c# parameterized sql"
You put Wrong bracket
INSERT INTO invoice (companyName,rate,svatNo,tinNo,line1,line2,city) VALUES ('" + this.txtname.Text + "','" + this.txtrate.Text + "','" + this.txtsvatno.Text + "','" + this.txttinno.Text + "','" + txtadline1.Text + "','" + txtadline2.Text + "','" + txtcity.Text + "');

Data type mismatch in criteria expression Oledb Access database

I'm getting the error:
Data type mismatch in criteria expression
When using this code. And using Access database.
OleDbConnection bab = new OleDbConnection();
bab.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\sdega\OneDrive\school\Werknemersdata.accdb;Persist Security Info=False;";
bab.Open();
try
{
OleDbCommand kaas = new OleDbCommand();
kaas.Connection = bab;
kaas.CommandText = "insert into Werknemersdata (Naam, Adres, Postcode, Woonplaats, Salaris) values ('" + txtNaam.Text + "', '" + txtAdress.Text + "', '" + txtpostcode1.Text + " " +txtpostcode2.Text + "', '" + txtwoonplaats.Text + "', '" + txtsalaris.Text + "') ";
kaas.ExecuteNonQuery(); // this is where it goes wrong
txtStatus.BackColor = Color.Green;
MessageBox.Show("data saved");
bab.Close();
}
catch (Exception ghakbal)
{
MessageBox.Show("Error" + ghakbal);
}
You missed one ' after '" + txtpostcode1.Text + " and one before " +txtpostcode2.Text + "' and also one , between them. It should be like this:
'" + txtpostcode1.Text + "' , '" +txtpostcode2.Text + "',
Also I strongly recommend that you always use parameterized queries to avoid SQL Injection. Like this:
kaas.CommandText = "insert into Werknemersdata (Naam, Adres, Postcode, Woonplaats, Salaris) values (?, ? ,.....");
kaas.Parameters.AddWithValue("Naam", txtNaam.Text);
kaas.Parameters.AddWithValue("Adres", txtAdress.Text);
//And other parameters...
Also It would be better to specify the type directly and use the Value property. Read more here.

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