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".
Related
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.
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...
I have an application that's built in .NET language.
In this application we mainly read/write to the database (SQL Server 2005).
Sometimes (for a single input) I just use the SQL query, for example:
commandText = "INSERT INTO Test_Table (Number) VALUES ('10')";
command = new System.Data.SqlClient.SqlCommand(commandText, connection);
command.ExecuteNonQuery();
If I want to update a bunch of records in my database, I use the SqlCommandBuilder class, as in this example:
adapter = new System.Data.SqlClient.SqlDataAdapter("SELECT * FROM Test_Table WHERE Number = '9'",connection);
commandbuilder = new System.Data.SqlClient.SqlCommandBuilder(adapter);
dataset = new System.Data.DataSet();
adapter.Fill(dataset,"Example");
dataset.Tables["Example"].Rows[0].["Number"] = 10;
adapter.update(dataset,"Example");
These work great. But now, for some reason I need to insert/update datetimes and use the CONVERT function on it.
The single SQL query works great:
t = System.DateTime.Now;
commandText = "INSERT INTO Test_Table (DateTime) VALUES (datetime, 't.toString()', 103)";
command = new System.Data.SqlClient.SqlCommand(commandText, connection);
command.ExecuteNonQuery();
This works without a problem, however I have no idea how to achieve the same thing using my SqlCommandBuilder scripts. I could change everything to single query, but this would take a week.
I have already tried the following, without success:
t = System.DateTime.Now;
adapter = new System.Data.SqlClient.SqlDataAdapter("SELECT * FROM Test_Table WHERE Number = '9'", connection);
commandbuilder = new System.Data.SqlClient.SqlCommandBuilder(adapter);
dataset = new System.Data.DataSet();
adapter.Fill(dataset, "Example");
dataset.Tables["Example"].Rows[0].["DateTime"] = "CONVERT(datetime,'" + t.toString() + "',103);
adapter.update(dataset, "Example");
This line of code is weird:
dataset.Tables["Example"].Rows[0].["DateTime"] = "CONVERT(datetime,'" + t.toString() + "',103);
Does it compile? Specifically, this:
.Rows[0].["DateTime"]
I think it should be:
.Rows[0]["DateTime"]
But regardles of the syntax...I don't think this is the right way to go. The datatable (in the dataset) expects a datetime object (btw, don't name your attributes by their datatype, it causes confusion) and you are providing it with something that is incompatible. Sytem.DateTime.Now returns a DateTime object, then you are concatenating it with string (again, does this compile?) and I assume you expect it to be injected into the INSERT statement?
Since you said that it would take a week to change everything, I assume that you have a lot of similar code to repair.
I see three possible solutions, all require some work:
Create a database trigger
https://msdn.microsoft.com/en-us/library/ms189799.aspx
Add a default value to the DateTime field in the database and remove the DateTime from the select query.
http://www.w3schools.com/sql/sql_default.asp
https://www.youtube.com/watch?v=INfi7jkdXC8
(start watching at around 2:00)
You can write a function that does the actual text replacing but it can get tricky:
dasdas as
private string ChangeDate(string insertQuery)
{
// find the location of the date column
// replace the actual value with the "CONVERT(datetime,'" + actualValue + "',103)"
// return the new value and store it in the sqlcommandbuilder.insertstatement
}
Admittedly, all three require work and are not really "elegant". I would go for option 2, because it seems less work. But I don't know if this solves your problem..
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
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)