I'm trying to insert the current date to the database and i allways get the message(when i press the button on the form to save to my access database), that the data type is incorect in the conditional expression.
the code:
string conString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=C:\\Users\\Simon\\Desktop\\save.mdb";
OleDbConnection empConnection = new OleDbConnection(conString);
string insertStatement = "INSERT INTO obroki_save "
+ "([ID_uporabnika],[ID_zivila],[skupaj_kalorij]) "
+ "VALUES (#ID_uporabnika,#ID_zivila,#skupaj_kalorij)";
OleDbCommand insertCommand = new OleDbCommand(insertStatement, empConnection);
insertCommand.Parameters.Add("#ID_uporabnika", OleDbType.Char).Value = users.iDTextBox.Text;
insertCommand.Parameters.Add("#ID_zivila", OleDbType.Char).Value = iDTextBox.Text;
insertCommand.Parameters.Add("#skupaj_kalorij", OleDbType.Char).Value = textBox1.Text;
empConnection.Open();
try
{
int count = insertCommand.ExecuteNonQuery();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
empConnection.Close();
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
}
I have now cut out the date,( i made access paste the date ), still there is the same problem. Is the first line ok? users.idtextbox.text?
Please help !
try Changing
insertCommand.Parameters.Add("#datum", OleDbType.Char).Value = DateTime.Now;
to
`insertCommand.Parameters.Add("#datum", OleDbType.Char).Value
= DateTime.Now.ToString("dd MMM yyyy HH:mm");`
( or some other acceptable date format)
Assuming that your database actually holds dates, and not strings, for the date column - I think you're trying to insert char values into your date column.
Change
insertCommand.Parameters.Add("#datum", OleDbType.Char).Value = DateTime.Now;
to
insertCommand.Parameters.Add("#datum", OleDbType.Date).Value = DateTime.Now;
I think you are getting issue due to the date format set in your regional settings and the date format accepted by MS Access.
You can use a specific date format as mentioned in following code.
DateTimeFormatInfo ukDTFomat = new CultureInfo("en-GB", false).DateTimeFormat;
DateTime.Now.ToString("yyyy-MM-dd", ukDTFomat);
You can simplify your OleDb usage by adding parameters like this:
OleDbParameter param = new OleDbParameter("#datum", DateTime.Now);
command.Parameters.Add(param);
This uses the override of the OleDbParameter that takes a string (the parameter name) and an object (whatever the value should be for the parameter). This lets OleDb figure out the correct parameter type for you (and saves you a lot of work typing and changing parameter types).
Update: just noticed this is Jet. All bets are off when it comes to Access, so I'm by no means sure the above will work.
You should use the type OleDbType.Date in the parameter. That maps to a DateTime value in .NET and an OLE date (internally represented as double) in the database. That's what Access uses for storing dates.
With any of the other date formats in OleDbType, it will be converted to a string representation that Access doesn't recognise as a date.
If you use OleDbType.Char the DateTime value will be converted to a string using the current culture in .NET, which may or may not be understood by Access depending on what the culture happens to be. In your case it seems that it was not understood.
Are you sure the problem is the date value? I.e., are the other columns really of type Char? For date values, you should use OleDbType.DBDate but you should also use the appropriate type for the other columns.
EDIT
Tested against an Access database with a date column, the following worked (although stripped the time obviously):
cmd.Parameters.Add( "#DateColumn", OleDbType.DBDate ).Value = DateTime.Now;
As well as (which included the time)
cmd.Parameters.Add( "#TestDate", OleDbType.Date ).Value = DateTime.Now;
EDIT As with the date parameters, you should be passing specific types for the other values:
insertCommand.Parameters.Add("#ID_uporabnika", OleDbType.Integer).Value = int.Parse( users.iDTextBox.Text );
insertCommand.Parameters.Add("#ID_zivila", OleDbType.Integer.Value = int.Parse( iDTextBox.Text );
insertCommand.Parameters.Add("#skupaj_kalorij", OleDbType.Integer).Value = int.Parse( textBox1.Text );
Related
On the server, the date format is mm-dd-yyyy. On my local machine, the date format is mm/dd/yyyy.
I have the following code:
DateTime FrDate, Todate;
string yy = "2020";
string mm = "04";
string dd = "01";
DateTime.TryParse(mm + "/" + dd + "/" + yy, out FrDate);
And then I am trying to run this query:
select * from helpdesk_tranactions where compl_date `= '" + FrDate.ToShortDateString() + "'
This is working fine when I run on my local machine, where the date format is mm/dd/yyyy.
However, when this code is deployed to the server, the same query is not working (since the date format is mm-dd-yyyy).
The error I get is:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
How can I write this query in such a way that it will work regardless of the system date formatting?
Noooooooo! If you're worried about string formats for SQL date values something has already gone horribly wrong.
The column in your database should be a Date, Timestamp, or DateTime rather than varchar field, and if that's true there is no human-readable format! The data is binary. What you see is a convenience shown to you by your management tool or connection library. If you're not using one of the date types for the column column, you should fix the schema, because it really is broken.
Once you have confirmed or fixed the column so you know it is a DateTime value, you should also be using DateTime variables in the C# code. And once you're doing that, the correct way to include those values in a query looks like this (assuming MySql because of the backtick, but you should also tag the question with the correct database engine):
string sql = "select * from helpdesk_tranactions where compl_date = #compl_date";
using (var cn = new MySqlConnection("connection string here"))
using (var cmd = new MySqlCommand(sql, cn))
{
cmd.Parameters.Add("#compl_date", MySqlDbType.DateTime).Value = FrDate;
cn.Open();
// ...
}
Notice this assigns the FrDate field directly to the query parameter. There's no conversion in your code to worry about.
This technique is also the best and only truly safe way to avoid certain other types of problem with sql.
I am trying to insert current time to a Time column in the excel using the below code through an oledb connection but when I check the excel the value inserted is in Date format.
Value updated in excel - 1/0/1900 3:54:11 PM
Expected Value - 3:54:11 PM
string currentTime = DateTime.Now.ToString("hh:mm:ss.fff tt");
string cmnd1 = "Create Table [" + currentDate + "] (TestCase char(100), ExecutionTime Time, Result char(20))";
string cmnd2 = "Insert Into [" + currentDate + "] (TestCase, ExecutionTime, Result) values ("+ "'" + tName + "',#dd,'" + result +"')" ;
using (OleDbConnection conn = new OleDbConnection(ConnectionStringtd))
{
OleDbCommand createSheet = new OleDbCommand(cmnd1, conn);
OleDbCommand insertResult = new OleDbCommand(cmnd2, conn);
insertResult.Parameters.AddWithValue("#dd", DateTime.Now.TimeOfDay);
conn.Open();
try
{
createSheet.ExecuteNonQuery();
}
catch(OleDbException) {}
insertResult.ExecuteNonQuery();
}
}
AFAIK, when you enter pure time value stored as a datetime with the entered time portion, and a date part will be January 0, 1900 automatically since the days before 1900 are incorrect in Excel.
Instead of that, pass your DateTime.Now directly to parameter and change your column format type to Time with h:mm:ss tt format in your format cells part. By the way, you just paramterized #dd part. Use parameters for the other values that you try to insert. Don't concatenate them.
insertResult.Parameters.AddWithValue("#dd", DateTime.Now);
And don't use AddWithValue anymore. It may generate unexpected and suprising results sometimes. Use Add method overload to specify your parameter type and it's size.
Also use using statement to dispose your commands as you did for the connection.
Which date format does T-SQL use? Does it rely on the system date? How can I be sure that my parameters are passed on correctly regardless of system date format. This question comes because of error:
Error converting data type nvarchar to datetime.
The SQL script in part:
CREATE PROCEDURE [dbo].[sz_pipeline04_pipelUpdte_inventory]
-- Add the parameters for the stored procedure here
#myFixDte datetime,
#doInsert bit
AS
BEGIN
The calling c# code:
public static DataTable GridInventory(string strdProcedureName, DateTime fixDate, bool execInsertYN)
{
DataTable dtbl_inventory = null;
try
{
dtbl_inventory = new DataTable();
using (var conn = new SqlConnection(cls_connRegistry.GetConnStrFull()))
using (var command = new SqlCommand(strdProcedureName, conn)
{
CommandType = CommandType.StoredProcedure
})
{
command.Parameters.Add("#myFixDte", SqlDbType.DateTime).Value = DateTime.Parse(fixDate.ToShortDateString());
command.Parameters.Add("#doInsert", SqlDbType.Bit).Value = execInsertYN;
conn.Open();
SqlDataReader dr = command.ExecuteReader();
dtbl_inventory.Load(dr);
conn.Close();
}
}
catch (Exception datawalile)
{ dtbl_inventory = null; }
return dtbl_inventory;
}
edited question.
The code you've now posted looks correct - except for one thing:
command.Parameters.Add("#myFixDte", SqlDbType.DateTime).Value = DateTime.Parse(fixDate.ToShortDateString());
As I've said in the comments, issues only come up around formatting when you convert to strings. So just do:
command.Parameters.Add("#myFixDte", SqlDbType.DateTime).Value = fixDate;
DateTimes (C#) and datetime (T-SQL) don't have a format. You get formatting issues when you convert them into strings. In their native representation, they're usually just a count of a number of events (ticks, milliseconds, etc) since some fixed point in the past. ADO.Net knows how to convert a DateTime into a SQL Server datetime.
If you have remaining conversion issues, it's in code you've not yet shown. But it will, again, be because you're converting away from the correct data type (datetime) and using strings.
This is not valid DATETIME format DD-MM-YYYY.
You can use CONVERT It in following:
DECLARE #myFixDte DATETIME
SET #myFixDte = CONVERT(DATE, N'30-12-2012', 104)
SELECT #myFixDte
Or you can SET It without converting in other format like YYYY-MM-DD
Try this:
#myFixDte = convert(datetime, '30-12-2012', 105)
And check the link provided by #N.Molderf
SQL Server recognizes one format always in same way, regardless which culture it using, and that format is YYYYMMDD.
So you can always use your dates in format 20120202 or 20151225, and SQL Server will parse that parameter using same mask.
Why you didnt tell as above c# datetime, here is a simple example for you how to solve this problem in your case it will be something like this
DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("dd-MM-yyyy HH:mm:ss");
or this one
DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss");
second one is a default
I am trying to add new information to a table, but it is giving me this Conversion failed error when converting date/time from character to string.
Here is part of my code:
try
{
string sp = "add";
comando.CommandType = CommandType.StoredProcedure;
comando.CommandText = sp;
comando.Parameters.Clear();
comando.Parameters.Add(new SqlParameter("#person", SqlDbType.VarChar));
comando.Parameters.Add(new SqlParameter("#reason", SqlDbType.VarChar));
comando.Parameters.Add(new SqlParameter("#information", SqlDbType.VarChar));
comando.Parameters.Add(new SqlParameter("#date", SqlDbType.DateTime));
comando.Parameters[0].Value = obj.person;
comando.Parameters[1].Value = obj.reason;
comando.Parameters[2].Value = obj.information;
comando.Parameters[3].Value = obj.date;
comando.ExecuteNonQuery();
}
catch (Exception exc)
{
throw exc;
}
To get the information of the date I am using obj.date = DateTime.Now; is this correct?
I don't recall how or why sometimes sending a plain date/time object into SQL won't work as we expect it.
The solution is to convert the date/time object to the universal ISO 8601 format: yyyyMMdd HH:mm:ss.fff - which SQL absolutely loves.
Here's a snippet which takes from J W's answer, which is actually demonstrating best practice:
const String UniversalDateTime = "yyyyMMdd HH:mm:ss.fff";
comando.CommandType = CommandType.StoredProcedure;
comando.CommandText = sp;
comando.Parameters.AddWithValue("#person", obj.person);
comando.Parameters.AddWithValue("#reason", obj.reason);
comando.Parameters.AddWithValue("#information", obj.information);
comando.Parameters.AddWithValue("#date", obj.date.ToString(UniversalDateTime));
// assuming connection is already open
comando.ExecuteNonQuery();
Upon SQL receiving the date/time string representation, the value will automatically be converted to SQL's internal date/time value.
PS. I recall also trying the ISO 8601 format using the T as separator: yyyyMMddTHH:mm:ss.fff. Try the version with the space, which worked for me when using the en-US SQL locale and non-en-US locales too.
Alternatively, you can use AddWithValue()
comando.CommandType = CommandType.StoredProcedure;
comando.CommandText = sp;
comando.Parameters.AddWithValue("#person", obj.person);
comando.Parameters.AddWithValue("#reason", obj.reason);
comando.Parameters.AddWithValue("#information", obj.information);
comando.Parameters.AddWithValue("#date", DateTime.Now);
// assuming connection is already open
comando.ExecuteNonQuery();
I unable to convert string to date, my string like 17/12/2012
Code written for this is shown below
public string Date_Convert(string dt1)
{
string strdate = string.Empty;
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
DateTime dt = Convert.ToDateTime(dt1);
strdate = dt.Month.ToString() + "/" + dt.Day.ToString() + "/" + dt.Year.ToString();
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
return strdate;
}
It is working fine in my local system. And not working in my server(which is located at Australia)of course I tried with different culture settings in the above code,
I'm using this date string in sql query in where condition.
please help me, It killed my one day time, and thanks in advance.
Instead of switching the culture, why don't you do something like this:
public string Date_Convert(string dt1)
{
DateTime dt = DateTime.ParseExact(dt1, "dd/MM/yyyy", new CultureInfo("en-GB"));
return dt.ToString("d", new CultureInfo("en-US"));
}
Also: If you use the value in an SQL query (and provided that your query works on a DATETIME field, not NVARCHAR), you should also consider using a parameterized query to pass the DateTime value to the database to avoid SQL injection.
For example:
DateTime value = DateTime.Parse(dt1, new CultureInfo("en-GB"));
using (SqlCommand cmd = new SqlCommand("SELECT ... FROM ... WHERE Date = #date", connection))
{
cmd.Parameters.AddWithValue("#date", value);
...
}
Try DateTime.ParseExact() it receives as parameter the pattern so for your case it would be "dd/MM/yyyy"
The format of the DataTime will depend on the current culture of your application. Inorder to have a specific format throught your application you can set the tag in the web.config file under section. In such case you need not write code to convert the datatime to proper format. By default all the dates will be set to the format specified.
http://forums.asp.net/t/1109183.aspx/1
More Info