Greetings,
I have the following code below which allows the date to be added via a JDBC connection as a STRING.
The value of dateString is inserted into the MS ACCESS database.
What is the easiest method to add the current date/time (dd/mm/yy hh:mm:ss) via JDBC in DATE format i.e. convert STRING to DATE or format the DATE without changing its type and insert it.
I'm a newbie to Java/Jsp too. -
<%@ page import="java.util.Date, java.text.SimpleDateFormat" %>
-
<% java.util.Locale locale = request.getLocale(); %>
-
-
<%
-
Date d = new Date();
-
String dateString = getFormattedDate (d);
-
%>
-
-
<%!
-
String getFormattedDate(Date d)
-
{
-
SimpleDateFormat simpleDate = new SimpleDateFormat("dd/MM/yy hh:mm:ss");
-
return simpleDate.format(d);
-
}
-
%>
-
Mar 13 '08
19 20250
Ok, I take your point about the code, it hasn't fallen on deaf ears!
I'm a university student and the code I've used is based on the examples that we are meant to modify.
Though the problem with my JDBC date insert I assume isnt related at all, once i get my code working I can then worry about other improvements.
I'm aiming to achieve some core functionality such as storing dates at the mo.
BigDaddyLH 1,216
Recognized Expert Top Contributor
Hmmm... I think that if you do it just with Statement, your SQL syntax depends on the database you're using. I've never touched ACCESS so I don't know the SQL syntax for it. If it were me, I'd say Statement be damned and use a PreparedStateme nt. Why do something inferior just because that was the model?
I changed it :) - String myquery = "INSERT INTO FAQ (\"category\", \"question\", \"answer\", \"sequence\", \"UserId\", \"created\") VALUES ('"+categoryParam+"','"+questionParam+"','"+answerParam+"', '"+sequence+"', '"+ session.getAttribute("theName")+"', '"+d+"' )";
-
PreparedStatement mystatement = conn3.prepareStatement(myquery);
At the moment it's not showing any errors but not actually inserting any records, so Im still investigating :)
Ahh now I understand what i have to do .. assign values and execute !
BigDaddyLH 1,216
Recognized Expert Top Contributor
Yikes! You are misusing Prepared Statement. The string should be: -
String myquery = "INSERT INTO FAQ (category, question, answer, sequence, UserId, created) VALUES (?,?,?,?,?,?)"
(note: all those quote marks only make it hard to read!)
Try reading the tutorial on prepared statement again. The last think you want to do is hardcode values into the prepared statement string -- it's whole reason for existence is to be parameterized.
Im thinking on my feet here .. - if(parameters.hasMoreElements()) {
-
-
String myquery = "INSERT INTO FAQ (\"category\", \"question\", \"answer\", \"sequence\", \"UserId\", \"created\") VALUES (?,?,?,?,?,?)";
-
PreparedStatement mystatement = conn3.prepareStatement(myquery);
-
-
mystatement.setString(1,request.getParameter("category"));
-
mystatement.setString(2,request.getParameter("question"));
-
mystatement.setString(3,request.getParameter("answer"));
-
mystatement.setInt(4,request.getParameter("sequence"));
-
mystatement.setObject(5,session.getAttribute("theName"));
-
mystatement.setDate(6,d);
-
-
ResultSet myresults = mystatement.execute();
-
}
When running I get THREE errors for the fields
Sequence (Integer in Database and INPUT TYPE = "Int)
theName (Session attribute the USER who logs in, STRING in Database)
D (Java Date, DATE/TIME in Database)
The exact errors are below :-
org.apache.jasp er.JasperExcept ion: Unable to compile class for JSP
An error occurred at line: 96 in the jsp file: /examples/wk465682AddFAQ. jsp
Generated servlet error:
The method setInt(int, int) in the type PreparedStateme nt is not applicable for the arguments (int, String)
An error occurred at line: 96 in the jsp file: /examples/wk465682AddFAQ. jsp
Generated servlet error:
The method setDate(int, java.sql.Date) in the type PreparedStateme nt is not applicable for the arguments (int, java.util.Date)
An error occurred at line: 96 in the jsp file: /examples/wk465682AddFAQ. jsp
Generated servlet error:
Type mismatch: cannot convert from boolean to ResultSet
No Idea which one is boolean, confused.com ??
Thanks for all your help, youre a lifesaver!
BigDaddyLH 1,216
Recognized Expert Top Contributor
If you feel you're in over your head, it's the fault of your course. At the very least, one should learn things one subject at a time. That's so obvious as to be self-evident. Now why do they have you mixing JSP with JDBC? You should have learned the JDBC first, in isolation. JDBC should never appear on a JSP, but that's a topic for another day...
These are all straightforward errors messages.
mystatement.set Int(4,request.g etParameter("se quence"));
You need to parse the String into an integer: - int sequenceValue = Integer.parseInt(request.getParameter("sequence"));
-
mystatement.setInt(4,request.sequenceValue);
mystatement.set Date(6,d);
You need to turn a java.util.Date into a java.sql.Date. A few glances at the API suggests: - java.sql.Date sqlDate = new java.sql.Date(d.getTime());
-
mystatement.setDate(6,sqlDate);
ResultSet myresults = mystatement.exe cute();
Only SELECT statements generate result sets. An update statement will return the
number of rows inserted, which will always be one, if it succeeds, so the
return value is not that useful. The preferred method to call is executeUpdate() ; - mystatement.executeUpdate();
:-)
I changed the string to int conversion to one line as it didnt work before to:- - mystatement.setInt(4,Integer.parseInt(request.getParameter("sequence")));
All running, it's resetting the time to 00:00:00 so I just need to check that out!!!
Thanks again for your help.
As for the module its a 12 wk module called Java and the Web, it states you dont have to have had any prior experience of Java to take it.
Its all about a dynamic website using a backend database.
Cheers
Rob
BigDaddyLH 1,216
Recognized Expert Top Contributor
I changed the string to int conversion to one line as it didnt work before to:- - mystatement.setInt(4,Integer.parseInt(request.getParameter("sequence")));
That's fine. It's a matter of taste if you should break a Java statement into smaller statements.
All running, it's resetting the time to 00:00:00 so I just need to check that out!!!
That's my fault. java.sql.Date corresponds to a SQL datatype that just specifies the day, not the time on that day as well. The solution is to use java.sql.Timest amp, in a similar way: - Timestamp ts = new Timestamp(d.getTime());
-
mystatement.setTimestamp(6, ts);
And double check that your ACCESS column type can hold the time as well as the date, but it should be okay.
Sorry, I will include the code for the SQL record insert which shows the Datestring value being passed in.
So to clarify I get the current date and time and insert into a record in my access database. - statement.executeUpdate("INSERT INTO FAQ (\"Id\",\"category\", \"question\", \"answer\", \"sequence\", \"UserId\", \"created\") VALUES ('"+IdParam+"','"+categoryParam+"','"+questionParam+"','"+answerParam+"', '"+sequence+"', '"+ session.getAttribute("theName")+"', '"+dateString+"') ");
-
Currently dateString is a string as in the database model and I want to convert the string into a date or have another method of inserting the current date (dd/mm/yy hh:mm:ss) into the database as a DATE rather than STRING.
Thanks
Rob
besides using prepared staements, maybe you want to know why your code doesn't work the way you tried.:
your code doesn't work, because you are inserting the date-string directly, without using any sql-conversion functions that will define the format. Like TO_DATE(dateStr ing, 'DD/MM/YYYY') in Oracle-database or str_to_date(dat eString, '%m/%d/%Y') in mySql-database. (I actually must look up the syntax of the formatting string for access-database).
So if you are not giving the date format, your database tries to convert the string by itself, using a "default" format
So most likey your administrator has defined a default data format for the database that is not the same as the data-string you have given.
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: JShurmatz |
last post by:
If anyone can shed some light on this problem I would greatly
appreciate it.
I am unsuccessfully trying to use a database connnection retrieved
from a pool configured using Java System Web Server 6.1 with the SQL
Server 2000 JDBC Driver.
The background:
1. I have downloaded the SQL Server 2000 JDBC Driver and installed it
on the web server.
|
by: CM |
last post by:
Hi,
when i want connect me in my BD with a JSP (with this simple code),
this exception is throw.
Thank's for ur help
Mathieu
CODE of my JSP
---------------------
|
by: dinesh prasad |
last post by:
I'm trying to use a servlet to process a form, then send that data to
an SQL server stored procedure. I'm using the WebLogic 8 App. server.
I am able to retrieve database information, so I know my application
server can talk to the database.
I've determined the failure occurs when the the following statement is
executed: cstmt.execute(); (due to the failure of println statements
placed afterwards). I get the following error after trying to...
|
by: Hassan Naqvi |
last post by:
Hi,
Basically, I am Java developer. In past I have played with Oracle
using Java (JDBC). But this is the time to play with IBM DB2 using
Java (JDBC). So kindly help this DB2 newbie.
I have a file of 32 MB, named as "fdbk5.0". This is actually a
database created in DB2 and containing records. I am interested in
viewing the *structure of this database, i.e. table names, column
names and finally all the records. How I can do this? Which...
|
by: Jobs |
last post by:
Download the JAVA , .NET and SQL Server interview with answers
Download the JAVA , .NET and SQL Server interview sheet and rate
yourself. This will help you judge yourself are you really worth of
attending interviews. If you own a company best way to judge if the
candidate is worth of it.
http://www.questpond.com/InterviewRatingSheet.zip
| |
by: mjahabarsadiq |
last post by:
HELLO FRIENDS
I HAVE ONE JAVA CODE WHICH PARSES AN XML FILE AND PRODUCE A QUERY TO CREATE TABEL IN A DATABASE.
BUT I NEED THE CODE TO BE USED IN A JSP PAGE.
HOW TO USE THIS PAGE WITH JSP.
I AM USING TOMCAT 4.1 WEBSERVER FOR COMPILING JSP PAGES.
|
by: vijaykumardahiya |
last post by:
Hello Sir,
I have a simple Issue but It is not resolve by me i.e input parameter
are not store in Ms-Access.
I store the input parameter through Standard Action <jsp:useBean>.
jsp:useBean call a property IssueData. this property exist in
SimpleBean which create a connection from DB and insert the data.
At run time servlet and server also show that loggging are saved in DB.
But when I open the table in Access. Its empty.
Ms-Access have...
|
by: asti1987 |
last post by:
I have a big problem, y need to print a jasper report, but it must to be with jsp.
this is my jsp
please help me
<%@ page import="java.io.*,java.util.*,java.net.*,java.sql.*,imprimir.imprimir" %>
<%
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |