SQLite command to insert current datetime not working through c# - c#

I am trying to insert current date in my table from a c# application, i am doing this the following way:
sqlite_cmd.CommandText = "INSERT INTO tablename (column1,creation_date) VALUES ('abcd_" + (id) + "',CURRENT_TIMESTAMP);";
sqlite_cmd.ExecuteNonQuery();
But this throws error saying that CURRENT_TIMESTAMP is not a valid field.
I double checked the above query using sqlite manager plugin for firefox and it seems to work correctly.
P.S. - id in the above query is an int variable that is set by c# application.

CURRENT_TIMESTAMP is only valid in column definition.
As a expression, you can use DATETIME('NOW'). Try:
sqlite_cmd.CommandText = "INSERT INTO tablename (column1,creation_date) VALUES ('abcd_" + (id) + "', DATETIME('NOW'));";

Try using this:
using(SQLiteCommand cmd = new SQLiteCommand(yourSqliteConnection))
{
cmd.CommandText = "INSERT INTO tablename (column1,creation_date) VALUES (?,?)";
cmd.Command.Parameters.AddWithValue("#p1",string.Format("abcd_{0}",id));
cmd.Command.Parameters.AddWithValue("#p2",DateTime.Now.ToString("s"));
cmd.CommandType= CommmandType.Text;
cmd.ExecuteNonQuery();
}
DateTime.Now.ToString("s") means convert this datetime into XSD format.
SQLite does not have a DateTime Format in its own. so everything you need is to convert it into a fixed format of TEXT and then insert and serach according to this format.
XSD is a fixed format for DateTime. it does not change if format of DateTime Change.
Remember when you need to do a search (SELECT) command based on DateTime try to convert it as shown above before doing any operation in SQLite.

Related

Checking if current date exists in database using c#

I have a table which I want to insert data in it only once in a day
and to implement that I want to check if current date already exists in
the database by writing these lines
DateTime date = DateTime.Now;
MySqlCommand cmd = new MySqlCommand("SELECT * FROM `attendances` WHERE
`lecture_id` = '" + lecture_id + "' " +
" AND `date` = '"+date.ToShortDateString()+"' ",con);
MySqlDataReader reader = cmd.ExecuteReader();
reader.Read();
if (reader.HasRows)
MessageBox.Show("you can't insert");
else MessageBox.Show("you can insert");
The date is inserted to the database in this format xxxx-xx-xx although using the same method for inserting, and date.ToShortDateString() returns the date in this format
xxxx/x/x .
I checked inserting the date manually in the correct format but that also didn't work, I also tried using the DATE function in sql but that didn't work either.
Just apply format string date = DateTime.Now.ToString("yyyy-MM-dd")
And do not call ToShortDateString() in your SQL query
You also should use SqlParameter as your code is vulnerable for SQL injection attack.
You could also avoid using .NET's DateTime and use MySql's NOW() or UTC_DATE() instead within your query, which may be better; if the region of your code and db reside in different timezones.
i.e.
[...] " AND `date` = DATE(NOW()) ",con);

How do I add a date using C# & SQL to an MS Access database with column type 'Date/Type'?

I have tried using a DateTimePicker with format dd/MM/yyyy to insert a date into a Date/Time column in my MS Access database using the insert SQL statement.
Here is what I have done:
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection; // Connecting the command to the connection.
command.CommandText = "insert into [TestEntry] (TestTableID, StudentID, DateOfTest, [DeadLine]) values(" + int.Parse(txtTestName.Text) + ", " + int.Parse(studentID) + ", #" + this.dateTimeStartD.Text + "# , #" + this.dateTimeEndD.Text + "#)";
command.ExecuteNonQuery();
connection.Close();
I keep getting the error
Input string was not in correct format
The Date/Time columns in my Access table are formatted as 'Short date' eg. 12/11/2015.
Any help will be appreciated.
I do not think its coming from database level. This exception is coming when you try to case value which in different format. Please check you first argument for the insert statement.
int.Parse(txtTestName.Text)
You are trying to insert integer value to "TestTableID" field by converting text box value to integer. Please check your text box input is number or characters. It should be only numbers.

SQLException: Error converting data type varchar to numeric

I am most likely missing something simple here since I am pretty new to this but I cannot figure this out.
I have a C# application that takes some user-entered data and updates a SQL Server database. One of the database fields I am updating is called "TransectLength" and has a datatype of 'decimal(5,1)'. The SQL looks like this:
string updateSQL = "UPDATE " + table1 + " SET TransectLength = NULLIF(#tl, '') WHERE ObjectID = #oid";
SqlCommand cmd = new SqlCommand(updateSQL, conn);
The parameter #tl:
cmd.Parameters.AddWithValue("#tl", dr["TransectLength"]);
dr is a DataRow. dr["TransectLength"] has a value of 2.5 and type is object{decimal}.
When I try:
cmd.ExecuteNonQuery();
I get the SQL Exception Error converting data type varchar to numeric.
Please see below for the parameter #tl. The SqlDbType is Decimal. If I enter nothing for TransectLength (i.e. dr["TransectLength"] value is {}) then the update query works just fine and appropriately enters a sql NULL value.
I also tried this:
cmd.Parameters.AddWithValue("#tl", Convert.ToDecimal(dr["TransectLength"]));
But nothing changed.
Thanks for your help.
Change NULLIF(#tl, '') to ISNULL(#tl, 0.0)

Error when updating date field in sql server using c#

I am trying to insert a date (date only, not datetime) into sql table (the datatype is date).
I am using the '23/07/2013' format which I am getting from jquery datepicker.
When I execute the following sql, I am getting following error.
SQL: UPDATE qmsAuditFindings SET FindDate='23/07/2013' WHERE AuditID=37
Please advise.
Also its worth mentioning that the insert statement with the exact format works just fine. Just the update that does not.
At the surface, this is simply a formatting issue - but "fixing the formatting" is the wrong way to address this; you should parameterize, such that formatting simply does not apply. Dates don't have a "format", as such - they are just numbers. For example, what we should probably execute is:
UPDATE qmsAuditFindings SET FindDate=#findDate WHERE AuditID=#auditId
To do that you get the DateTime value in your .NET code, and do something like:
DateTime findDate = ...
int auditId = ...
using(var cmd = connection.CreateCommand()) {
cmd.CommandText =
"UPDATE qmsAuditFindings SET FindDate=#findDate WHERE AuditID=#auditId";
cmd.Parameters.AddWithValue("findDate", findDate);
cmd.Parameters.AddWithValue("auditId", auditId);
cmd.ExecuteNonQuery();
}
or more simply with a tool like "dapper":
DateTime findDate = ...
int auditId = ...
connection.Execute(
"UPDATE qmsAuditFindings SET FindDate=#findDate WHERE AuditID=#auditId",
new { findDate, auditId });

Error: The conversion of a nvarchar data type to a smalldatetime data type resulted in an out-of-range value

Hey all I'm trying to do the following insert query
SqlDataSource userQuizDataSource = new SqlDataSource();
userQuizDataSource.ConnectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=quizApp;Integrated Security=True";
userQuizDataSource.InsertCommand = "INSERT INTO [UserQuiz] ([DateTimeComplete], [Score], [UserName]) VALUES (#DateTimeComplete, #Score, #UserName)";
userQuizDataSource.InsertParameters.Add("DateTimeComplete", DateTime.Now.ToString());
userQuizDataSource.InsertParameters.Add("Score", score.ToString());
userQuizDataSource.InsertParameters.Add("UserName", User.Identity.Name);
int rowsAffected = userQuizDataSource.Insert();
Buti keep getting the following error:
The conversion of a nvarchar data type
to a smalldatetime data type resulted
in an out-of-range value.
The statement has been terminated.
Can anyone help me out?
What does your statement DateTime.Now.ToString() return??
What language and regional settings is your SQL Server expecting??
Do you have a mismatch there??? Maybe your .NET returns a MM/dd/yyyy format, while SQL Server expects dd/MM/yyyy (or vice-versa).
Try this code in your SQL Server:
DECLARE #test TABLE (smalldate SMALLDATETIME)
INSERT INTO #test VALUES ('02/21/2010 22:00:32') --
SELECT * FROM #test
Replace my string there with what output you got from .NET's DateTime.Now.ToString() - does this work? Does SQL Server give you a better error message?
Next, try to use the ISO-8601 format for dates (YYYYMMDD) - this works for ALL regional and language settings in SQL Server - does this work??
DECLARE #test TABLE (smalldate SMALLDATETIME)
INSERT INTO #test VALUES ('20100221 22:00:32') --
SELECT * FROM #test
I had the same problem adding datetime.now into my SQL server column 'Date' set to datatype SmallDateTime.
To resolve it was quite simple (after many attempts!!)
string currentdatetime=
DateTime.Now.Year + "." + DateTime.Now.Month + "." + DateTime.Now.Day +
" " + DateTime.Now.Hour+(":")+DateTime.Now.Minute+(":")+DateTime.Now.Second
This will return the date into the format that the Server will expect
Try changing this:
userQuizDataSource.InsertParameters.Add("DateTimeComplete", DateTime.Now.ToString());
to this:
userQuizDataSource.InsertParameters.Add("#startdate", SqlDbType.DateTime, DateTime.Now.ToString());
Try no converting your date to string:
userQuizDataSource.InsertParameters.Add("DateTimeComplete", DateTime.Now);
Edit: Try this then:
userQuizDataSource.InsertParameters.Add("DateTimeComplete", TypeCode.DateTime, DateTime.Now.ToString());
There is another way to just pass the actual object, but I can't remember.. sorry.
In Windows 8, if you are facing this problem even after changing Formats in below location
Control Panel -> Region
You still have to transfer these settings to your users. In the same window, go to tab "Administrative", click on copy settings.
Select the appropriate check boxes and click OK.

Categories