Saving DateTime value into microsoft access database - c#

I am trying to save some data to access DB but the date is stored in incorrect format
dbCommand.CommandText = "insert into Clients(Name,Gender,PhoneNumber,ReciveServiceDate)
values ('" + name_txtBox.Text + "','" + gender_comBox.Text + "',"
+ long.Parse(phone_txtBox.Text) + ","
+ (recive_dateTimePicker.Value).ToShortDateString() + ");";

Listen to Jon's advice.
However, if you insist, you can do it like this:
+ (recive_dateTimePicker.Value).ToString("#yyyy'/'MM'/'dd#") + ");";

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?

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!

SQL query exception issue

Am trying to insert a record into my database using a function that consists of 11 arguments as input. The function is as follows:
public int check_in_visitor(int visitor_id,String date_in, String date_out,
String time_in, int check_in, int check_out, String employer,
String vehicle_number, int manual_entrychk, String time_out)
The corresponding query for it:
String query = "insert into visitor values('"+visitor_id +"','" +
date_in + "','" + date_out + "','" + time_in + "'," + check_in +
",'" + check_out + "'," + employer + ",'" + vehicle_number + "'," +
manual_entrychk + ",'" + time_out + "')
its always giving errors like expression incorrect! Please help me solve the issue
Use SqlParameter..
That way you would avoid sql injection attack,enclosing data with ' or " & other issues..
String query = "insert into visitor values(#visitor_id,#date_in,#date_out,#time_in,#check_in,#check_out,#employer,#vehicle_number, #manual_entrychk,#time_out)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.Add(new SqlParameter("visitor_id", visitor_id));
command.Parameters.Add(new SqlParameter("date_in", date_in));
....
command.ExecuteNonQuery();
You are missing to close the Query String with double quotes.
String query = "insert into visitor values('"+visitor_id +"','" + date_in + "','" + date_out + "','" + time_in + "'," + check_in + ",'" + check_out + "'," + employer + ",'" + vehicle_number + "'," + manual_entrychk + ",'" + time_out + "')";
Note1 : all VARCHAR feilds should be enclosed in single quotes properly.
Note 2: all INT feilds should not be enclosed with single quotes.
Note 3: your query is open to SQL injection attaks. please use parameterised queries.
untill unless you provide the feild types its defficult to solve the problem.
use string.format. Like string query = string.Format("insert into visitor values ('{0}','{1}'...",vistor_id ...); This syntax is a lot easier to troubleshoot and avoids the string concatenations. You should also consider not using data that's not fully trusted in your query (like anirudh mentioned in his reply), if that's an option at all.
if query below doesnt help you, please tell what is the error returned?
string query = "insert into visitor values ("+visitor_id+ ","+ date_in +","+date_out
+","+time_in+","+check_in+","+check_out+","+employer+","+vehicle_number+","
+manual_entrychk+","+time_out+")";

missing ";" in insert query c# access database

string query = "insert into TraineeDetail values('" + trainee.TyNo + "','" +
trainee.PersonalNumber.ToString() + "','" + trainee.TraineeName.ToString() + "','" +
trainee.Rank.ToString() + "','" + trainee.Division.ToString() + "','" + trainee.ENMATEL + "','" +
trainee.ENMATMECH + "','" + trainee.ENMATGSC + "','" + trainee.MAXM.ToString() + "','" +
trainee.SUBBR.ToString() + "') order by MAXM desc ";
i m getting error- missing semicolon (;) at the end of the sql statement
any solution
INSERT statements are used for just that. Inserting data.
You appear to be using it combined with an ORDER BY. What do you intend to order?
ORDER BY is generally used when you are SELECT'ing data. As in, "I want this data, but order it in this way before you show it to me".
Remove the ORDER BY and your query will work.
Please also investigate SQL injection and SqlParameters. As it is, your code is very insecure.

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

Categories

Resources