I am developing a simple hospital management system for my project with netbeans, so here is my problem in brief. When a patient admits and discharge from a hospital his/her date of admission and date of discharge should be recorded. so I put two jDateChoosers for admission and discharge. So when a new patient admits I have to keep the date of discharge jDateChooser blank and save.
I changed the date format of the jDateChoosers to "yyyy-MM-dd"
(I use mysql control center 0.9.4 to create my database and tables) firstly I tried saving the date by changing the discharge column(dod) data
type to 'date' then an exception jumped as follows.
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data truncated for column 'dod' at row
Then I tried changing the data type to 'varchar' and allowed null
values, ok no problem this time it saved blank in the db.
When retrieving patients' info I have coded the admission and discharge date to appear in the two jDateChoosers seperately. but an exception generates like this
java.text.ParseException: Unparseable date: ""
at java.text.DateFormat.parse(DateFormat.java:357)
at Patient.pidKeyReleased(Patient.java:455)
at Patient.access$000(Patient.java:23)
at Patient$1.keyReleased(Patient.java:118)
at java.awt.Component.processKeyEvent(Component.java:6466)
This is the code and the imports involved with the date problem :
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;`
This is coded in the save button
try {
Statement stmt = connection.hosp().createStatement();
String dt = ((JTextField)doa.getDateEditor().getUiComponent()).getText();
String dt1 = ((JTextField)dod.getDateEditor().getUiComponent()).getText();
stmt.executeUpdate("insert into patients values ('"+pid.getText()+"','"+nic.getText()+"','"+fname.getText()+"','"+lname.getText()+"','"+age.getText()+"','"+address.getText()+"','"+contact.getText()+"','"+ptype.getSelectedItem()+"','"+wardname.getText()+"','"+wardno.getText()+"','"+roomno.getText()+"','"+diagnosis.getText()+"','"+doctor.getText()+"','"+consultant.getText()+"','"+dt+"','"+dt1+"')");
} catch (Exception e) {
e.printStackTrace();
}
This is the search Code and it is coded in a text box and the action is keyrelease.
This is where the above stated exception java.text.ParseException: Unparseable date: "" comes.
try {
Statement s = connection.hosp().createStatement();
String ss = pid.getText().trim();
ResultSet rs = s.executeQuery("select * from patients where patient_id like ('%"+ss+"%')");
while(rs.next()){
nic.setText(nics);
fname.setText(fnames);
lname.setText(lnames);
.... etc
String datevalue=rs.getString(16);
String datevalue1=rs.getString(17);
DateFormat formatter ;
Date date, date1;
formatter = new SimpleDateFormat("yyyy-MM-dd");
date = (Date)formatter.parse(datevalue);
date1 = (Date)formatter.parse(datevalue1);
doa.setDate(date);
dod.setDate(date1);
}
}catch (Exception e) {
e.printStackTrace();
}
if there is any other method to solve this problem please mention it.
You still havent provided all the information, So I am assuming. Anyhow this is what I have found.
dt and dt1 columns are numbered as 15 and 16 from your insert statement.
String datevalue = rs.getString(16); // Supposed to be 15
String datevalue1 = rs.getString(17); // Supposed to be 16
While getting data from columns use rs.getXXX("Column Name") (gives more visibility) instead of rs.getXXX("columnIndex").
Also use JDBC PreparedStatement. Currently your app does not avoid SQL Injection
Try not to use varchar for date datatype. Use Date Thats what they were designed for.
Related
I am planning to add 'Date' objects into the SQLite database. However, I am getting an error about the insertion being null.
The error is this
org.sqlite.SQLiteException: [SQLITE_CONSTRAINT_NOTNULL] A NOT NULL constraint failed (NOT NULL constraint failed: dates.Tarih)
at org.sqlite.core.DB.newSQLException(DB.java:909)
at org.sqlite.core.DB.newSQLException(DB.java:921)
at org.sqlite.core.DB.execute(DB.java:825)
at org.sqlite.jdbc3.JDBC3PreparedStatement.execute(JDBC3PreparedStatement.java:53)
This is my code. I suspect from the question marks. Because when I remove them and place them with 'now'. It actually works. But, the following code throws the above error.
Insert method
public static void insert(Date date, Date date2) {
try{
System.out.println(" date:"+date.toString());
String query = "insert into dates(Tarih,Tarih2) values(strftime('%d-%m-%Y',?), strftime('%d-%m-%Y',?))";
pst=conn.prepareStatement(query);
pst.setObject(1,date);
pst.setObject(2,date2);
pst.execute();
}catch (SQLException e){
e.printStackTrace();
}
}
Probably you have defined the column Tarih as NOT NULL and your code is trying to insert a null value in the table.
The reason that you get null from strftime() is because you don't pass a valid date for SQLite.
For SQLite valid dates/datetimes are either strings in the format yyyy-MM-dd hh:mm:ss, or integer unix epoch times or floating point numbers representing julian days.
What you pass are Date objects and this is your mistake.
One way to solve the problem is to extract from each of the Date objects an integer representing unix epoch time and pass that to strftime():
public static void insert(Date date, Date date2) {
try{
long d = date.toInstant().toEpochMilli() / 1000;
long d2 = date2.toInstant().toEpochMilli() / 1000;
String query = "insert into dates(Tarih,Tarih2) values(strftime('%d-%m-%Y', ?, 'unixepoch'), strftime('%d-%m-%Y', ?, 'unixepoch'))";
pst=conn.prepareStatement(query);
pst.setLong(1, d);
pst.setLong(2, d2);
pst.execute();
} catch (SQLException e){
e.printStackTrace();
}
}
I have an column defined as datetime(2) and I have to create a new date in this format - 2016-01-01T19:33:15-05:00
Entity: private Date transactionTime;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date date = null;
try {
date = formatter.parse(formatter.format(new Date()));
} catch (ParseException e) {
e.printStackTrace();
}
obj.transactionTime(date);
It is getting inserted in SQL as like this - "2021-08-26 14:19:09.0000000" but I need insert this in the format mentioned above.
There is only column type, datetimeoffset that can hold the timezone offset (e.g. -05:00 as mentioned in your question) value. Check the Data type mappings documentation to learn more about it.
So, if you want to store the timezone offset value, change the column type to datetimeoffset. After that, you will be able to insert the value which you have mentioned in the question.
You can use the following code to access the stored value:
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT foo FROM mytable WHERE ...");
while (rs.next()) {
DateTimeOffset dateTimeOffset = rs.getObject(1, DateTimeOffset.class));
System.out.println(dateTimeOffset);
}
rs.close();
st.close();
where foo the name of the column of type, datetimeoffset.
I made a software using the java language and MS SQL Server as the database. The problem am facing is that when I search for a date range using two dates, it's giving items which I have not requested.
For example, if I need items from 1st to 7th October, it includes items on the 11th, 12th, 13th, 14th, 15th, 16th, etc.
the date format am using MMM d,yyyy
I have used the following code
String val1 = ((JTextField)jdate1.getDateEditor().getUiComponent()).getText();
String val2 = ((JTextField)jdate2.getDateEditor().getUiComponent()).getText();
String sql = " select * from Report_details where Date between '"+val1+"' and '"+val2+"' ";
// conn is some Connection
PreparedStatement myStmt = conn.prepareStatement(sql);
ResultSet rs = myStmt.executeQuery();
if(rs.next()){
// do stuff
}
Do not trust user input.
String sql = "select * from Report_details where Date between ? and ?";
....
Date dt1 = new SimpleDateFormat("MMM d,yyyy").parse(val1);
// better yet, have your date picker return a Date object
....
myStmt.setDate(1, dt1);
....
should be the way to go (or setTime or setTimestamp, depending on your table definition)
NB: do not copy paste this, just a hint to get you off in the right direction.
Can anyone help me with a sample JSP code to store date in a MySql database through JDBC?
When I try to execute the code given below, I get the following exception:
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '' for column 'date' at row 1
How to overcome this problem? Following is my code:
Connection con = null;
String StaffName = request.getParameter("StaffName");
// String subcode = request.getParameter("subcode");
String hourId = request.getParameter("hourId");
if (hourId == null)
hourId = "";
String day = request.getParameter("day");
if (day == null)
day = "";
String date = request.getParameter("date");
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/StaffAllocation", "root", "success");
// PreparedStatement stat = con.PrepareStatement();
String updateString = "INSERT INTO tblstaffallocation (StaffName,hourId,daysId,date) VALUES (?,?,?,?)";
PreparedStatement preparedStatement = con.prepareStatement(updateString);
preparedStatement.setString(1, StaffName);
preparedStatement.setInt(2, 0);
preparedStatement.setInt(3, 0);
preparedStatement.setString(4, date);
} catch (Exception e) {
out.print(e);
}
To set date to prepared statement you need change type of value:
String date = request.getParameter("date");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // your template here
java.util.Date dateStr = formatter.parse(date);
java.sql.Date dateDB = new java.sql.Date(dateStr.getTime());
now convert String date to java.sql.Date and use another method:
preparedStatement.setDate(4,dateDB);
I had a similar error. It turns out I just needed to update the jar version for mysql-connector-java (using maven)
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>...</version>
</dependency>
Try reformating the date
String date = new SimpleDateFormat("yyyy-MM-dd")
.format(new Date(request.getParameter("date")));
and then insert into the database.
Note that request.getParameter("date") should be in format 11/20/2013 for this to work or you can use a similar way to achieve.
Make sure that the Date value that you are trying to insert into the table is exactly in the format defined in the date column of your table.
I know this is an old thread, but none of these solutions solved the problem for me. What worked for me was to upgrade hibernate to version 5.2.10.Final (see this SO post).
Running Spring Boot and Spring Data JPA 1.5.4.RELEASE and hibernate 5.2.10.Final.
If someone will have similar error for entity field with Data type annotated as #Temporal, the solution for me was to replace annotation value TemporalType.TIMESTAMP by TemporalType.TIME:
#Temporal(TemporalType.TIMESTAMP)
private Date dateField;
should be like this:
#Temporal(TemporalType.TIME)
private Date dateField;
Another way to resolve this problem without any changes in code (at least for me) was to run application on higher Tomcat version, hope it will help.
Accepted answer only handles date, not datetime. Anyways...
My problem was it didn't accept really old datetime's. I generated date in .net environment, where default date was "1900-01-01 01:01:01". I had to change date to somthing later in time... Ooops.
My error message:
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '1900-01-01 01:01:01' for column 'added' at row 1
I have a database in which I am saving messages with tiemstamps. I have table created with this code:
CREATE TABLE messages (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
msgid VARCHAR(64) UNIQUE,
payload TEXT,
sender VARCHAR(255),
cur_timestamp TIMESTAMP(3)
);
This all works perfectly. However, now I am trying to delete some rows with timestamp older than some specified by user. This is done in Java part of my system like this:
// get current timestamp
Date date = new Date();
// timestamp has to be in the same format as in database
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd h:mm:ss.SSS");
String formattedDate = sdf.format(date);
System.out.println("Current time: " + formattedDate);
// subtract desired time
if (msgOld.equals("hour")) {
date.setTime(date.getTime() - ONE_HOUR_MILLISCONDS);
formattedDate = sdf.format(date);
} else if (msgOld.equals("day")) {
date.setTime(date.getTime() - ONE_DAY_MILLISCONDS);
formattedDate = sdf.format(date);
}
This, too, works fine - the constants look like this: final long ONE_HOUR_MILLISCONDS = 60 * 60 * 1000;
The only problem is that I dont know how to write the query in JDBC. I tried doing this:
// prepare query
String query;
if (msgOld.equals("all")) {
query = "TRUNCATE TABLE messages";
} else {
query = "DELETE FROM messages WHERE cur_timestamp < " + date + ";";
}
but it says I have an error in my SQL statement (the second one, the one with TRUNCATE works fine). I tried putting formattedDate instead of date in the statement, too.
Whats wrong with it (probably something really simple - maybe difference between java.util.Date and SQL timestamp...)? Thanks for any tips!
EDIT: Thanks for all responses... I have rewritten the code so it uses prepared statement like this:
// prepare query
String query;
PreparedStatement pstmt = null;
try {
if (msgOld.equals("all")) {
query = "TRUNCATE TABLE messages";
pstmt=conn.prepareStatement(query);
} else {
query = "DELETE FROM messages WHERE cur_timestamp < ?;";
pstmt = conn.prepareStatement(query);
pstmt.setString(1, timestamp.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
try {
pstmt.execute();
System.out.println("Successfully deleted messages.");
pstmt.close();
} catch (Exception e) {
System.out.println("Error with db query.");
e.printStackTrace();
}
but I am still getting SQL exception (even if I convert date to timestamp and like this Timestamp timestamp = new Timestamp(date.getTime()); and use it in the satement)
You cannot just concatenate java.util.Date objects into query string. That's wrong.
Better use PreparedStatement for this kind of things.
Take a look at this tutorial for example
exactly as #Funtik said preparedStatement could be used.
See this link here
it would not exactly sove your problem but you will get a clear idea.