After i create an insert statement i want to know two values, the last inserted id and the date.
This is my insert statement
cmd.CommandText = "INSERT INTO message (user_id, category_id, media) " +
"VALUES (:user_id, :category_id, :media)" +
"RETURNING id, TO_DATE(TO_CHAR(creation_date, 'YYYY-MM-DD HH24:MI:SS'), 'YYYY-MM-DD HH24:MI:SS') INTO :last_insert_id, :last_creation_date";
The parameter
cmd.Parameters.Add(new OracleParameter()
{
ParameterName = ":last_creation_date",
OracleDbType = OracleDbType.Date,
Direction = ParameterDirection.Output
});
When i try to get the date, only the year, month and day returns with 00:00:00...
DateTime.Parse(cmd.Parameters[":last_creation_date"].Value.ToString())
How can i receive the full datetime from the value?
A couple of things:
Take a look at the docs for OracleDbType. You are using OracleDbType.Date, which maps to an Oracle DATE type - which is just a date. You should probably use OracleDbType.TimeStamp, or whatever type matches the column you're working with.
Mitch is correct in the question comments. You have entirely too much conversion to and from strings. In the vast majority of cases, you should not use a string to represent a date or time in a database, or in the client code that communicates with a database. Your SQL should change simply to:
RETURNING id, creation_date INTO :last_insert_id, :last_creation_date
Likewise, your .NET code should be similar to:
DateTime dt = (DateTime) cmd.Parameters[":last_creation_date"].Value;
Related
So the date in my DGV table showed this format (12/31/2022 12:00:00 AM) I tried to get rid of the time to make it (12/31/2022) when I did that my date format got messed up it became (202,231,12). How do I fix it?
cm = new MySqlCommand("SELECT OrderID, FORMAT(Orderdate, '%Y-%m-%d') as OrderDate, CustomerID, Username, ProductID, Qty, Price, TotalAmount FROM ordertb WHERE OrderDate LIKE'%" + txtSearch.Text+"%'", con);
You will never get it right if you try to post a string for searching over a column of type date. Instead you should use parameters to avoid SQL Injection and to avoid parsing problems on the string passed to the database.
First you need to check if the input is indeed a datetime value. (the exact format to pass at the TryParseExact depends on your current inputs)
if (!DateTime.TryParseExact(txtSearch.Text, "MM/dd/yyyy HH.mm", CultureInfo.CurrentUICulture,
DateTimeStyles.None, out DateTime searchedDate)
... not a date, display error, return....
// Prepare the sql command avoiding string concatenations but
// using parameters placeholders.
cm = new MySqlCommand(#"SELECT OrderID, OrderDate, CustomerID,
Username, ProductID, Qty, Price, TotalAmount
FROM ordertb
WHERE OrderDate = #searchedDate", con);
// Add the parameter and its value. Note that we will require
// a parameter of type date and just the date part of the datetime variable.
cm.Parameters.Add("#searchedDate", MySqlDbType.Date).Value = searchedDate.Date;
.... execute the query....
And to set the format for a specific DataGridView column use
(for example the third column)
dataGrid.Columns[2].DefaultCellStyle.Format = "MM/dd/yyyy";
Finally, if your column OrderDate stores also the time, then you should use a sligthly different WHERE condition
....
WHERE OrderDate >= #startDate and OrderDate < #endDate", con);
cm.Parameters.Add("#startDate", MySqlDbType.Date).Value = searchedDate.Date;
cm.Parameters.Add("#endDate", MySqlDbType.Date).Value = searchedDate.Date.AddDays(1);
Simply use the DATE_FORMAT() function to perform date formatting.
DATE_FORMAT(YourTableFieldName,'%m/%d/%Y')
In your case: cm = new MySqlCommand("SELECT OrderID, DATE_FORMAT(Orderdate, '%m/%d/%Y') as OrderDate, CustomerID, Username, ProductID, Qty, Price, TotalAmount FROM ordertb WHERE OrderDate LIKE'%" + txtSearch.Text+"%'", con);
Get more help from w3schools
I am inserting date into database, and I get this error
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
My database is like
column datatype
-----------------
id int
date datetime
My current date format is DD/MM/YYYY. but it didn't accept. When I changed format (made changes in system calender not in programming) to YYYY/DD/MM, it works.
Why does the above format not work?
My query is
cmd = new SqlCommand("insert into tblnewaccount values ('" + id + "','" + dateTimePicker1.Text + "')", con);
cmd.ExecuteNonQuery();
Why does the above format not work?
I honestly don't care and neither you should. Because you are doing something terribly wrong here than using the right format.
You try to save your DateTime values with their string representation in a datetime typed column. You should always choose the right data type for your values.
Bad habits to kick : choosing the wrong data type
First, don't use Text property of your DateTimePicker, use Value property to get the value as a DateTime. And you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
using(var con = new SqlConnection(conString))
using(var cmd = con.CreateCommand())
{
cmd.CommandText = #"insert into tblnewaccount
values (#id, #date)";
cmd.Parameters.Add("#id", SqlDbType.Int).Value = id;
cmd.Parameters.Add("#date", SqlDbType.DateTime).Value = dateTimePicker1.Value;
con.Open();
cmd.ExecuteNonQuery();
}
It wont work because it will be recognized as a string instead of a valid DateTime object value. You can try converting it to a valid datetime format so that it can recognize it. Also, you can show the text value as dd/MM/yyyy like you are showing now, but pass the value parameter in your query if it gives you a proper datetime format.
Have a look into Conversion from string to datetime as well. That will give you clear idea in this case.
Hope this helps.
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.
string queryStr = "SELECT * from Task_Report_Table where convert(varchar, date, 105) between '" + txtStartDate.Text.ToString() + "' and '" + txtEndDate.Text.ToString() + "' ";
This is the Query I am Using for Retriving the Value from database.
In database table Task_Report_Table have the coloums date,Name,Task and Hours.Here Date is Datetime datatype ,So In Query Convert into String and Iam matching th
I have an UI With Start date and End Date .By giving the date in UI .The above Mention Query Will have to display the Records.
If Iam Giving Start date 07-07-2012 and end date as 12-07-2012.It displays the Values in between 07-07-2012 and 12-07-2012 values.But The Thing is that It displaying Next month and previous months Records and Next year and previous year records also If the records present in database.
The Prob's is It validating day only.but not Month and Year.
I need to validate for day,month,year Which iam Giving in the UI.
You do NOT want to ever write the SQL like that, don't concat strings together, it's so easy to hack (with SQL injection) a site with this kind of code.
Try this:
SELECT * from Task_Report_Table where date between #startdate and #enddate
and then add startdate and enddate as SqlParameter to the SqlCommand you're using, like so:
SqlCommand command = new SqlCommand(yourSQL, connection);
command.Parameters.Add(new SqlParameter("startdate", DateTime.Parse(txtStartDate.Text)));
command.Parameters.Add(new SqlParameter("enddate", DateTime.Parse(txtEndDate.Text)));
The Prob's is It validating day only.but not Month and Year. I need to
validate for day,month,year
This convert(varchar, date, 105) will give you a string that looks like this 27-07-2012 not a date. So your query compares strings not dates.
Use date parameters as suggested by #SteenT.
try like this
put two variables for textboxes..
txtStatrdate.text=strdate;
txtEndDate.text=enddate ;
CONVERT(VARCHAR(10),date,101) BETWEEN CONVERT(DATETIME,strdate,101) AND
CONVERT(DATETIME,enddate,101)
I have A anb B in String format
A = 14/01/2007
B = 22:10:39
I try to insert date and time:
SQL = "insert into MyTbl(Tdate,Ttime) value ('" + Convert.ToDateTime(A) + "','" + Convert.ToDateTime(B) + "')";
i got ORA-01843 error, what I can do ?
thank's in advance
Don't use raw SQL to insert values. Use a parameterized query instead. Parse your strings into .NET DateTime (or DateTimeOffset) and TimeSpan values in the normal way, and then use something like:
string sql = "insert into MyTbl(Tdate,Ttime) values (:date, :time)";
using (OracleCommand cmd = new OracleCommand(sql, connection))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("date", OracleType.DateTime).Value = date;
cmd.Parameters.Add("time", OracleType.IntervalDayToSecond).Value = time;
cmd.ExecuteNonQuery();
}
(Obviously adjust for the types of your actual fields.)
The error is due to the month, try:
TO_DATE(A, 'DD/MM/YYYY')
Remember that Oracle doesn't have a time-only field.
You're trying to insert a time-only field into a datetime. My guess is that the CLR is turning B into 00/00/00 22:10:39, which isn't a valid oracle date. For example:
SQL> select to_date('00/00/00', 'MM/DD/YY') from dual;
select to_date('00/00/00', 'MM/DD/YY') from dual
*
ERROR at line 1:
ORA-01843: not a valid month
Either way, Convert.ToDateTime(B) probably isn't returning the right thing.
Also, this:
"insert into MyTbl(Tdate,Ttime) value ("
should be this:
"insert into MyTbl(Tdate,Ttime) values ("
...but I'm guessing that's just a typo here.
However i tried Jon method, it didnt work for me for date also time. So i found this method for datetime. Maybe that helps someone in next future too.
OracleParameter oPrm;
oPrm = cmd.CreateParameter();
oPrm.ParameterName = ":myDate";
oPrm.OracleDbType = OracleDbType.Date;
oPrm.Value = DateTime.Now; //for date
cmd.Parameters.Add(oPrm);