I am using mvc and I want to insert a date to an oracle database. I stored the value
in an object then add it to a collection (processed_date). I then used the insert statement
to write to the database.
All I get it invalid date format. Do you have any idea how I can fix this? I need to write the exact date "31/12/2099" to the Oracle database.
object col14Value = "31/12/2099";
processed_date = (col14Value).ToString()
string sqlIns = "insert into price_line (processed_date) values (to_date(:processed_date, mm/dd/yyyy)
The property of the processed_date looks like this
public string processed_date { get; set; }
Now I am begining to the the error below
[Oracle.DataAccess.Client.OracleException] = {"ORA-01843: not a valid month"}
mm/dd/yyyy should be encased in quotes - 'mm/dd/yyyy'. It is an Oracle string. Also if your date is 31/12/2099 then your format string should be 'dd/mm/yyyy'
Related
How to add parameters in a SQL select query?
string time = 2013-09-25 00:00:00;
I wish to use the time variable in the below mentioned SQL query
Select LastUpdated from Employee where LastUpdated > time;
Try this:
string sqlDate = time.ToString("yyyy-MM-dd HH:mm:ss.fff");
It appears what the OP is asking is how to convert a VARCHAR to a DATETIME in SQL Server not actually a String to DateTime in C#.
You will need to use the following to convert to a DATETIME:
SELECT LastUpdated
FROM Employee
WHERE LastUpdated > CONVERT(datetime, varTime, 121);
See the following MS Reference for more information.
To echo others though, you should just pass the parameter in as a datetime and let the database provider factory handle the conversion of appropriate types, or add a new method that actually returns a DateTime. In the future, I wouldn't name a method GetUpdateTime unless it actually returns a type of Time.
You can convert your string in C# code to DateTime using
DateTime.TryParse() or Convert.ToDateTime()
OR
Convert VARCHAR to DATETIME in SQL using
Convert(datetime, time)
I just framed my question in a wrong, the query remains the same though. I just wanted time to be added as a paramter in my SQL-query. The code for the same looks like
String commandText = "Select LastUpdated from Employee where LastUpdated > :time;";
OracleConnection connection = new OracleConnection(connectionString);
OracleCommand command = new OracleCommand(commandText, connection);
command.Parameters.Add("time", time);
Thanks a lot for your help!
My bad that I couldn't frame the question properly.
The following class captures SendQueue objects from API json responses:
public class SendQueue
{
public DateTime SendDate { get; set; }
public int StatusCode { get; set; }
public string StatusMessage { get; set; }
}
When I receive the object, I convert the SendDate value to string to insert into a MySQL database, but the formatting apparently is not accepted by the DB and so the insert fails.
When I convert the value to string, the formatting of the SendDate is "dd/MM/yyyy hh:mm:ss" whereas the database accepts "yyyy-MM-dd hh:mm:ss".
Of course, a better way of handling this is via parameterized queries. But since I am using batch inserts, I am unable to use DateTime objects.
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
I will have the same problem if I use Bulk Insert as well since the dates will eventually be converted to strings stored in a file.
You should use an appropriate DateTime type in your schema. Do not use strings to represent Dates or DateTimes or Times, numbers, or anything else that is not a native string.
MySql allows for the following schema types:
DATE
TIME
DATETIME
TIMESTAMP
YEAR
In this case the most appropriate one would be DATETIME. This aligns with the .net type System.DateTime. If you are using ADO.NET then you should be using parameters in your queries. Example:
using(MySqlCommand m = new MySqlCommand("INSERT INTO table (sendDate) VALUES (#sendDate)"))
{
m.Parameters.Add("#sendDate", MySqlDbType.DateTime).Value = myObj.SendDate;
// rest of code
}
Batch Insert
You do not have to run one insert statement at a time. You can easily create one statement with multiple tuples that you want to insert. Here is sample c# code that does that with 1 column. You can easily extend this with multiple values per tuple.
var sql = "INSERT INTO table (sendDate) VALUES (";
var parameters = input.Select((queue, i) => new MySqlParameter("#sendDate" + i.ToString(), MySqlDbType.DateTime)).ToArray();
sql += string.Join("), (", parameters.Select(_ => _.ParameterName)) + ")";
for (int i = 0; i < parameters.Length; i++)
{
parameters[i].Value = input[i].SendDate;
}
using(var connection = new MySqlConnection(connectionString))
using(var command = new MySqlCommand(sql, connection))
{
command.Parameters.AddRange(parameters);
connection.Open();
command.ExecuteScalar();
}
When to convert?
The code stack should always convert a DateTime to a string as late as possible up the call stack, generally in the Presentation Layer (at the point a Human has to read it). The reverse is also true, a string input should be converted to a DateTime as early as possible going down the call stack (so again, in the presentation layer).
Why not varchar for Dates?
If you are wondering why you should not store DateTime as a string see this previous answer: When to use VARCHAR and DATE/DATETIME. I'll quote the important stuff:
Some of the disadvantages of the VARCHAR version:
You can't easily add / subtract days to the VARCHAR version.
It is harder to extract just month / year.
There is nothing stopping you putting non-date data in the VARCHAR column in the database.
The VARCHAR version is culture specific.
You can't easily sort the dates.
It is difficult to change the format if you want to later.
It is unconventional, which will make it harder for other developers to understand.
In many environments, using VARCHAR will use more storage space. This may not matter for small amounts of data, but in commercial environments with millions of rows of data this might well make a big difference.
Time Zones and Values
Do not forget about time zones if this is applicable to your application. It is recommended to always store a DateTime UTC value in the database instead of a local timezone value. The UTC value can then be sent to the presentation layer where the presentation layer is responsible for applying the local time zone to the value (optional). Some UI frameworks have built in mechanisms for doing this in the DateTime controls. Again, the reverse is also true, have the presentation layer convert any input to a UTC DateTime value and send that back down the call stack to the server.
Per your updated question, it seems the root issue is that you need a way to insert multiple rows via a single insert statement.
Ideally you'd provide a stored procedure which could accept a table type as input, as could be done in the SqlServer world: Insert entire DataTable into database at once instead of row by row?
Given that's not an option for MySQL at time of writing however, there are a few alternatives...
If you need to do this because you need all rows to be inserted in the same transaction, simply wrap your inserts in a transaction. Code would be something like this (untested as I don't have MySQL).
public void InsertMySql(string connectionString, string command, DataTable data)
{
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
try
{
using (MySqlCommand cmd = new MySqlCommand(command, connection))
{
cmd.CommandType = CommandType.Text;
foreach (var row in data.Rows)
{
cmd.Parameters.Clear();
foreach (var cell in data.Columns)
{
cmd.Parameters.AddWithValue($"#{cell.Name}", row[cell]);
}
cmd.ExecuteNonQuery();
}
}
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
}
}
If you need to do this for performance reasons, another option may be to look into a third party library such as: https://github.com/zzzprojects/Bulk-Operations. I've not tried this personally, but the library looks promising / the publisher (zzzprojects) are quite well known and respected / maintain the popular site SQL Fiddle amongst other projects.
public static void InsertMySql(string connectionString, DataTable data)
{
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
var bulk = new BulkOperation(connection);
bulk.BulkInsert(data); //assumes your data table's table name, column names/definitions match your table's; I think. See https://bulk-operations.net/bulk-insert for what documentation's available
}
}
I have select query in SQLite Database. There is a LogInTime field that datatime datatype.
Here is AccessDate variable passing date "11/16/2016" like format
string sql = "SELECT * FROM Tble_Login where LogInTime = '" + AccessDate + "'";
The SQLite Tble_Login looking like this,
After excute this query, no data? How can I get data?
Referring to the SQLite documentaion you should use following format for AccessDate
YYYY-MM-DDor YYYY-MM-DD HH:MM or YYYY-MM-DD HH:MM:SS. On the documentation page you can find more formats in the section Time Strings
You can also try to use the BETWEEN statement like in this question
string sql = #"SELECT * FROM Tble_Login where LogInTime BETWEEN ""2016-11-16"" AND ""2016-11-17""";
I am currently trying to do a Select in my SQL Server database using a parameter with Datetime type. But I need this parameter only has the format YYYY-MM-DD date because of the following query in SQL I'm using and it's working :
select
idCliente, DescCliente, DescAnalista , StatusChamado , DataAtendimento
from
Atendimento
where
cast ([DataAtendimento] as date) = '2016-04-27';
I read several posts indicating that I use DbType or .ToString but when running it is generating error alleging failure to convert the string to the date / time format.
This is how I use the SqlParameter:
DateTime date;
date = Data;
try
{
sqlClient.Command.Parameters.AddWithValue("#adate", date);
sqlClient.Command.CommandText = #" select idCliente, DescCliente, DescAnalista , StatusChamado , DataAtendimento from Atendimento where cast ([DataAtendimento] as date) = '#adate';";
I need a help from you guys , I'm not finding any means that can perform this select
You have to remove the '' in = '#adate'. With the '' in place, it effectively turns your query into:
select
idCliente, DescCliente, DescAnalista , StatusChamado , DataAtendimento
from Atendimento
where cast ([DataAtendimento] as date) = '#date';
This means that cast([DateAtendimento] as date) is compared against the string '#date', thus the conversion to date error.
I want to add lotno,date,catid,rcno from a table lot and local c# variables buyid,prc,datetime, all to the table soldlot. How do I do this? Im using MySql.
string datetime = DateTime.Today.ToString("yyyy-MM-dd");
String q6 = "insert into soldlot (lotNo,date,categoryId,receiptNo) (select #lotno,date,#catid,#rcno from lot)";
MySqlCommand c6 = new MySqlCommand(q6, cn);
c6.Parameters.Add("#lotno",lotno);
c6.Parameters.Add("#catid",catid);
c6.Parameters.Add("#buyerId", buyid);
c6.Parameters.Add("#rcno", rcno);
c6.Parameters.Add("#soldPrice", prc);
c6.Parameters.Add("#soldDate", datetime);
c6.ExecuteNonQuery();
When you say;
select #lotno,date,#catid,#rcno from lot
You try to parameterize your column names, not your values.
You need to use them like;
select lotno, date, catid, rcno from lot
where lotno = #lotno and date = #date and catid = #catid and rcno = #rcno
Read 13.2.5 INSERT Syntax
And looks like you don't need #buyerId, #soldPrice and #soldDate because you didn't even define them in your command.
If you wanna save your DateTime values, don't store in any character typed column. Use datetime or relevant type and pass your DateTime values directly to your parameterized queries.
Also use using statement to dispose your database connections and objects as well.