Not able to insert date in JDBC - sql

The database I am working with has the date format as
DD-MON-RR
This is the table:
CREATE TABLE dependent (
Fname varchar2(15) not null,
bdate date,
);
I am currently trying to insert into a database using JDBC with the code
String insert = "INSERT INTO DEPENDENT(Fname,bdate) VALUES(?,?)";
PreparedStatement p = z.conn.prepareStatement(insert);
p.setString(1, "Billy");
String formatIn = "DD-MMM-YY";
SimpleDateFormat sdfi = new SimpleDateFormat(formatIn);
java.util.Date inDate = sdfi.parse("29-AUG-10");
java.sql.Date sqlDate = new java.sql.Date(inDate.getTime());
p.setDate(2, sqldate);
p.executeUpdate();
I thought this would fit the format expected, however it keeps giving me java.sql.SQLException: Io exception: Size Data Unit (SDU) mismatch
I'm unsure how to fix this

Believe it or not, it looks as though your error has to do with the pattern you are using with SimpleDateFormat. Change the following:
String formatIn = "DD-MMM-YY";
SimpleDateFormat sdfi = new SimpleDateFormat(formatIn);
java.util.Date inDate = sdfi.parse("29-AUG-10");
to this and the problem should go away:
String formatIn = "dd-MMM-yy";
SimpleDateFormat sdfi = new SimpleDateFormat(formatIn);
java.util.Date inDate = sdfi.parse("29-AUG-10");
The D and Y speciciers denote the day in year and week year, respectively, and are probably not what you intended to use (see here: Y returns 2012 while y returns 2011 in SimpleDateFormat).
Note that the rest of your JDBC code looks OK to me.

Related

SQL Statement - Java

I've been trying to come up with a couple of SQL statements on how to get this right but no luck. I've tried between, >= and =<. Basically, the SQL statement that I've used is working but to an extent only.
My code works like this: the user will choose a date range (from date and to date) and the program will retrieve and show the data it has within those range. Like I said, it works but it also shows the days from the other months when what I want to show is just those particular days that the user picked. eg. from July 1, 2016 to July 5, 2016. What's happening is any month of the year that has those dates will show as well which makes that particular method a bit useless.
Any help or any explanation why is this so would be appreciated.
Below is my code:
stringFromDate = sdf.format(fromDate.getDate());
stringToDate = sdf.format(toDate.getDate());
String query = "Select * from tblSavings where date between '" + stringFromDate+ "' and '" + stringToDate+"'";
try{
pstmt = conn.prepareStatement(query);
rs = pstmt.executeQuery();
tblList.setModel(DbUtils.resultSetToTableModel(rs));
You can use SimpleDateFormat to get a string which is in proper format to be used as a date in SQLite, the proper format being yyyy-MM-dd:
String pattern = "yyyy-MM-dd";
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
String stringFromDate = dateFormat.format(fromDate.getDate());
Seems like you're trying to re-invent the wheel here. PreparedStatements were created exactly for this usecase - setting variable values in a predefined structure. In your case, with the setDate method. From the context I'm guessing your fromDate and toDate variables are java.util.Date instances, so you'll have to convert them to java.sql.Dates
java.sql.Date fromDateToBind = new java.sql.Date(fromDate);
java.sql.Date toDateToBind = new java.sql.Date(toDate);
String query = "Select * from tblSavings where date between ? and ?";
try{
pstmt = conn.prepareStatement(query);
pstmt.setDate(1, fromDateToBind);
pstmt.setDate(2, toDateToBind);
rs = pstmt.executeQuery();
// use the results...
} // etc...

How to separate Date and time from DateTime method in ASP.Net

I am writing my SQL query to insert date and time and I want to separate date and time from DateTime method now. I want to store them in a table of my database separately. How I could insert them separately, please guide me.
Here is my incorrect query:
string CheckRequest = "select count(*) from Requests where Date='"+DateTime.Now.ToString()+"'";
DateTime variables in .NET are not 'separable' in date and time parts. They always contains the date and the time (hence the name). What you probably need is to query the database using only the Date part of your query. You could reach your result converting your DateTime variable to a string with just the date part using a special formatting pattern for the ToString method when applied to a DateTime variable
string CheckRequest = #"select count(*) from Requests
where Date='" +DateTime.Now.ToString("yyyy-MM-dd")+"';
but this still leaves an open problem.
Passing a formatted string requires that you format it exactly as your database expects it. Failing to accurately represent the string leads to a failure in retrieving records in the datatable.
A better approach is letting your database engine figure out the Date value from a DateTime variable using a parameterized query.
Something like this
string CheckRequest = #"select count(*) from Requests
where Date=#myDate"
using(SqlConnection cn = new SqlConnection(.......))
using(SqlCommand cmd = new SqlCommand(CheckRequest, cn))
{
cn.Open();
cmd.Parameters.Add("#myDate", SqlDbType.Date).Value = DateTime.Now.ToDay;
object result = cmd.ExecuteScalar();
if(result != null)
{
int count = Convert.ToInt32(result);
MessageBox.Show("Record found=" + count.ToString());
}
else
MessageBox.Show("No Record found");
}
Here I am using a parameter of type Date and assign the Now.ToDay (still a DateTime value but with the time equals to 12:00:00 AM) The database engine now knows to use only the Date part and query your table correctly

Trouble converting DateTime (.net) to datetime (SQL server)

I'm trying to pass a string (from a text file) - '17/07/99' into a sql server table - the destination is a date column.
the insert is in a string, of the form:
Dim cmd As New SqlCommand(...yada...)
cmd.CommandText = "INSERT INTO my.table (thisDate, ...etc... ) VALUES (#myDate, ...etc...)"
I am adding the parameters to the cmd using:
cmd.Parameters.Add("#myDate", SqlDbType.DateTime).Value = Date.ParseExact("11/11/11", "dd/MM/yy", CultureInfo("en-GB"))
When I come to ExecuteNonQuery
I get cannot convert string to datetime error.
I thought the ParseExact was doing the conversion from string to DateTime??
Do I really need to do a CONVERT in the sql as well as using datetime structures ?!
Try this:
cmd.Parameters.Add("#myDate", SqlDbType.DateTime).Value = new DateTime(2011, 11, 11);
And also see this:
http://msdn.microsoft.com/en-us/library/w2sa9yss(v=vs.110).aspx
just tested this and it works ... you only need to format your date if you want it consistent no matter what culture your OS is otherwise you don't have to do that
you can use this way
Dim d As Date = "17/07/99"
or you can use this way
Dim d As Date = "17.07.99"
if you only have date without time then it doesn't matter what you use
you can either use this
cmd.Parameters.Add("#myDate", SqlDbType.DateTime).Value = d
or this
cmd.Parameters.Add("#myDate", SqlDbType.Date).Value = d
i just tried both versions mixed and no error whatsoever and rows inserted
Try formatting the string before adding it.
Format(YourTimeStringHere, dd-MM-yy)

2nd Date Parameter Throws ORA-01843: not a valid month error

I have a query where I need to check a date between two dates using Oracle. Whenever I run the code I get an ORA-01843: not a valid month error. However whenever I remove either of the two parameters from the sql it works fine, but trying to use two date parameters throw an error. What am I missing?
StringBuilder sql = new StringBuilder();
DateTime yearBegin = new DateTime(Convert.ToInt32(taxYear) + 1, 1, 1);
DateTime yearEnd = new DateTime(Convert.ToInt32(taxYear) + 1, 12, 31);
sql.Append(
"SELECT * FROM TABLE WHERE FIELD = '1099' AND CREATED_DT >= TO_DATE(:createdYearBegin, 'MM/DD/YYYY') AND CREATED_DT <= TO_DATE(:createdYearEnd, 'MM/DD/YYYY') AND SSN = :ssn");
try
{
using (OracleConnection cn = new OracleConnection(ConfigurationManager.AppSettings["cubsConnection"]))
using (OracleCommand cmd = new OracleCommand(sql.ToString(), cn))
{
cmd.Parameters.Add("ssn", ssn);
cmd.Parameters.Add("createdYearBegin", yearBegin.ToShortDateString());
cmd.Parameters.Add("createdYearEnd", yearEnd.ToShortDateString());
cn.Open();
OracleDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
ret = dr.HasRows;
}
}
think you've got a problem with your parameter's order.
If you don't bind parameters by name, they are bound by position (means the order in which you add parameters is taken).
Just try to add :
cmd.BindByName = true;
You expect date formatted as MM/DD/YYYY, but it is not guaranteed that ToShortDateString() returns it in this format. A format specifiction is needed. But well, I do not even know what is the programming language you are using to provide further help...
Print out the results of ToShortDateString and you'll see what happens. Also, i agree with "you should provide a format because you can't rely on the default".

Convert value from string to date format in SQL Server 2008

I want to convert date which is stored as string in a SQL Server 2008 database to smalldatetime.
The format for the saved string is 16/12/2007 and I want to remove / and replace it with - to get proper date format which is 16-12-2007
I getting the following error
Conversion from string "16/12/2007" to type 'Date' is not valid.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Conversion from string "16/12/2007" to type 'Date' is not valid.
Source Error:
Line 34: NewsItem.Visible = True
Line 35: NewsItem.Date_Modified = CDate(GetContent.Ndate)
Line 36: NewsItem.Date_Published = CDate(GetContent.Ndate)
I thought of creating a function that replace the / character with - to then update the database but it will take long time.
Don't use strings if you actually want to store datetime/smalldatetimes. Use sql-parameters to avoid localization/format issues and - more important - to prevent sql-injection. A VB.NET Date can be used for a smalldatetime column. Use Date.TryParse to validate and parse the string.
Dim sql = "INSERT INTO dbo.TableName(Date_Modified)VALUES(#Date_Modified);SELECT CAST(SCOPE_IDENTITY() AS INT);"
Using con = New SqlConnection("Connection-String")
Using cmd = New SqlCommand(sql, con)
Dim dt As Date
If Not Date.TryParse(GetContent.Ndate, dt) Then
MessageBox.Show("please enter a valid date")
Return
End If
cmd.Parameters.AddWithValue("#Date_Modified", dt)
Dim newID = cmd.ExecuteScalar() ' presuming that you have an identity column that is autoincremented
End Using
End Using
Retrieve the date as string from database and then use Date.ParseExact which Converts the specified string representation of a date and time to its DateTime equivalent.
Dim ydate = "16/12/2007"
Dim edate As Date = Date.ParseExact(ydate, "dd/MM/yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo)