Database query issue - java

Relatively new to using database and for some reason I can't get this 'execute' to work.
statment2.execute("insert into table Value (" + int + "," + date + "," + int + ",'" + string + "')");
The error I get is "missing a comma". The date is designated as dates only in that particular field.
I set it up as follows
Date date = new Date();
date.setMonth(month);
date.setYear(year);
date.setDate(weekStart); //weekStart is always monday
Do I need to use just plain old date or date.toString? I was going to use Calendar but I don't know how to set a DB date using the Calendar object. I didn't see a "gety/m/d" method.
So, is the problem my query or am I improperly using the Date object to set the date in the database?
Edit:
Tried the response, got incorrect format - Expected Date got number.
Tried
sqlDate.valueOf(dateString I created)
sqlDate.toString()
sqlDate
Using a preparedStatement wouldn't fix this would it? I realize it's supposed to be better for security reasons.

First, you should use a PreparedStatement to insert values in your query. This has many advantages including avoiding SQL Injection issues. If you use PreparedStatement, you will be avoid the errors that you are seeing now. Your code using PreparedStatement would something like this:
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String query = "insert into table (column1,column2,column3,column4) values(?, ?, ?,?)";
pstmt = conn.prepareStatement(query);
pstmt.setInt(1, 1);
pstmt.setDate(2, sqlDate);
pstmt.setInt(3, 3);
pstmt.setString(3, "test");
pstmt.executeUpdate();
} catch (Exception e) {
//log the error messages log.error(e,e);
//throw the actual exception upstream
} finally {
pstmt.close();
conn.close();
}
I am not sure what you meant by "DB" date. If you are after the sql date object you can convert a java.util.Date object to a java.sql.Date object this way:
java.util.Date date = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(date.getTime());

Related

org.postgresql.util.PSQLException: ERROR: column is of type date but expression is of type integer: cannot write date into postgres using java

I'm trying to insert a record inside my table but I cannot insert any values into the Date column.
This is the code I use to make an insert:
Connection connection = DatabaseConnection.getInstance().getConnection();
ResultSet result = null;
try
{
Statement statement = connection.createStatement();
statement.executeUpdate(query,Statement.RETURN_GENERATED_KEYS);
result = statement.getGeneratedKeys();
} catch (SQLException e)
{
e.printStackTrace();
}
finally
{
return result;
}
How I call this function:
String authorName = "Paul"
String authorSurname = "Mac"
DateTimeFormatter f = DateTimeFormatter.ofPattern( "yyyy-MM-dd" ) ;
LocalDate date = LocalDate.parse ( "2017-09-24" , f );
"Insert into autore(nome_autore, cognome_autore, datanascita) values('"+authorName+"', '"+authorSurname+"', "+date+")")
The fullstack trace I get:
org.postgresql.util.PSQLException: ERROR: column "datanascita" is of type date but expression is of type integer
Suggerimento: You will need to rewrite or cast the expression.
Posizione: 90
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2676)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2366)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:356)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:496)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:413)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:333)
at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:319)
at org.postgresql.jdbc.PgStatement.executeUpdate(PgStatement.java:1259)
at org.postgresql.jdbc.PgStatement.executeUpdate(PgStatement.java:1240)
at projectRiferimentiBibliografici/com.ProjectRiferimentiBibliografici.DatabaseConnection.QueryManager.executeUpdateWithResultSet(QueryManager.java:113)
at projectRiferimentiBibliografici/com.ProjectRiferimentiBibliografici.DAOImplementation.AuthorDaoPostgresql.insertAuthor(AuthorDaoPostgresql.java:136)
at projectRiferimentiBibliografici/com.ProjectRiferimentiBibliografici.Main.MainCe.main(MainCe.java:43)
The correct solution to this problem is to use a PreparedStatement - do not concatenate parameters into SQL strings.
Your problem with the date parameter is only the tip of the iceberg.
The next problem you'll get is, if Peter O'Donnel signs up.
So you should use something like this:
String authorName = "Paul";
String authorSurname = "Mac";
DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.parse("2017-09-24", f);
String insert = "Insert into autore(nome_autore, cognome_autore, datanascita) values(?,?,?)";
PreparedStatement pstmt = connection.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, authorName);
pstmt.setString(2, authorSurname);
pstmt.setObject(3, date, java.sql.Types.DATE);
pstmt.executeUpdate();
There is a way to solve this. In the place Where is you specify the jdbc url.
Ex:
"jdbc:postgresql://host/schema"
Change above to
"jdbc:postgresql://host/schema?stringtype=unspecified"
Then your db determine type of your params not the jdbc driver.
Here you are using direct insert sql statement. As you are appending date object to string it will be converted to date.toString() which might not be expected format in sql.
Below is the insert sql statement:
"Insert into autore(nome_autore, cognome_autore, datanascita)
values('"+authorName+"', '"+authorSurname+"', '2017-09-24')")
Note: This approach of sql query building is not recommended and open to SQL Injection. Better to use PreparedStatement or an ORM framework.

how can insert date value from jDateChooser to sql database

1- a me tried in this way
String sql = "insert into transport(s_id,transport_date)" +
" values ( + jTextField2.getText()+","
+ ((JTextField)jDateChooser1.getDateEditor().getUiComponent()).getText() +")";
pst=con .prepareStatement(sql2);
pst.executeUpdate();
2- and this way
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
String date=sdf.format(jDateChooser1.getDate());
String sql = "insert into transport(s_id,transport_date)" +
" values ( + jTextField2.getText()+","
+ date +")";
in #run
examble today choose : 2021-5-27
will insert 1989 !
Using + to place data in an SQL statement is EXTREMELY DANGEROUS. Aside from cross-site scripting, it is one of the greatest sources of hacks and vulnerabilities in software! For a more detailed explanation, search the web for “SQL injection”.
Do not, under any circumstances, place data in an SQL statement using concatenation (using + or StringBuilder or StringBuffer or Formatter or any other similar string construction mechanism).
The only safe way to add user-supplied data to a database statement is with PreparedStatement. The String argument you pass to prepareStatement must not have any data in it. Instead, you place question marks (?) in the String, to act as placeholders for data; then you use the various set* methods of PreparedStatement to replace each question mark with data. This allows the PreparedStatement to guarantee safety.
Instant instant = jDateChooser1.getDate().toInstant();
LocalDate date = instant.atZone(ZoneId.systemDefault()).toLocalDate();
String sql = "insert into transport(s_id,transport_date) values (?, ?)";
pst = con.prepareStatement(sql);
pst.setString(1, jTextField2.getText());
pst.setObject(2, date);
pst.executeUpdate();

Oracle: convert java date to Oracle date in java program

I have a java program that reads the date as string from an input file and updates the Oracle table, where this date is part of an index fields.
I tried the following options:
a) Reading the data from csv file delimited by ; as String
109920541;2013-01-17 11:48:09;EDWARD ANTHONY;
b) Using SimpleDateFormat convert String to Date in a routine:
java.text.SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date dt = formatter.parse("2013-01-17 11:48:09");
c) Use this date to prepare my sql stmt:
String update_query = "UPDATE "+ tableName +" SET NAME = ? WHERE ID = ? AND DATE_TIME = ?";
java.sql.Connection conn = java.sql.DriverManager.getConnection(dbUrl, dbUser, dbPwd);
java.sql.PreparedStatement pstmt = conn.prepareStatement(update_query);
if (dt not null) {
pstmt.setObject(1, new java.sql.Timestamp(dt.getTime()),java.sql.Types.DATE);
}
pstmt.executeBatch();
d) This does not find the date which is a part of key and so the data is not updated.
In sql developer I use the below query to fetch row:
SELECT * FROM table
WHERE ID = '1099205410'
AND DATE_TIME = TO_DATE('2013-01-17 11:48:09', 'YYYY-MM-DD HH24:MI:SS');
How to convert a java String to Oracle date?
Thanks.
For a single line:
pstmt.setString(1, name);
pstmt.setInt(2 id);
pstmt.setTimeStamp(3, ew java.sql.Timestamp(dt.getTime()));
pstmt.executeUpdate();
If the DATE_TIME value is not always present in the CSV data, simply use a second PreparedStatement; with just 2 parameters.
If you are using a loop reading the lines, do
for ... {
...
pstmt.clearParameters();
pstmt.setString(1, name);
pstmt.setInt(2 id);
pstmt.setTimeStamp(3, new java.sql.Timestamp(dt.getTime()));
pstmt.addBatch();
}
pstmt.executeBatch();
You might consider using the new time APIs.
(UPDATE is for existing records.)

When I enter an old date (e.g., 20/03/1961 (dd/mm/yyyy) the value one day earlier is stored

I am using MySQL, Eclipse, GWT java and when I enter an old date 20/03/1961 (dd/mm/yyyy) the value stored is 19/03/1961. I get the same result irrespective of whether I manually input the date or use the date picker (i.e., it displays as 20/03/1961 on input but when I redisplay it displays as 19/03/1961). I have checked the DB (MySQL) and it is stored as 1961-03-19. In the DB the column is defined as date and collation is utf8_general_ci.
The error seems to only occur between certain date ranges. On the 12/12/2014 # 11:24 I tested by halving dates back and I found the error on 4/4/1971, i.e., 5/4/1971 was stored correctly and 4/4/1971 was stored as 3/4/1971. I then entered the original date I had trouble with, 31/3/2004 and the error occurred (i.e., it was stored as 30/3/2004). I have been trying various other dates and found 3/4/2007 is stored as 2/4/2007 while 4/4/2007 is OK. a mathematical genius could probably find a pattern to this.
The relevant code is:
Client side:
final DateBox dateBoxDOB = new DateBox();
//dateBoxDOB = new DateBox();
dateBoxDOB.setFormat(new DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
flexTable.setWidget(0, 1, dateBoxDOB);
dateBoxDOB.getDatePicker();
java.sql.Date sqlDOB = new java.sql.Date(dateBoxDOB.getValue().getTime());
AsyncCallback<Void> callback = new UpdateHandler<Void>(EditYouthMemberView.this);
rpc.updateYouthMember(cd_ID, textBoxSurname.getText(), textBoxFirstName.getText(), sqlDOB,
imagePath, sqlDateArchived, integerBoxScoutNumber.getValue(), sd_ID, "Cubs",
"Explorer", sqlPackIn, sqlDatePackOut, callback);
Server side:
public void updateYouthMember(String cd_id, String surname,
String firstname, java.sql.Date dob, String photograph, java.sql.Date archived,
Integer scout_no, String sd_id, String section, String pack, java.sql.Date startDate,
java.sql.Date endDate) {
PreparedStatement ps = null;
PreparedStatement ps2 = null;
// Create connection/statement variables outside of try block
Connection c = null;
String updateWithoutPhoto = ("UPDATE at_cub_details " +
"SET cd_surname = ?, " +
"cd_first_name = ?, " +
"cd_dob = ?, " +
"cd_archived = ?, " +
"cd_scout_no = ? " +
"WHERE cd_id = ?;");
String updateWithPhoto = ("UPDATE at_cub_details " +
"SET cd_surname = ?, " +
"cd_first_name = ?, " +
"cd_dob = ?, " +
"cd_photograph = ?, " +
"cd_archived = ?, " +
"cd_scout_no = ? " +
"WHERE cd_id = ?;");
try {
// Get Connection and Statement from DataSource
c = ds.getConnection();
try {
if (photograph == null) {
// Create a statement and execute the query on it
ps = c.prepareStatement(updateWithoutPhoto);
ps.setString(1, surname);
ps.setString(2, firstname);
ps.setDate(3, (java.sql.Date) dob);
ps.setDate(4, (java.sql.Date) archived);
ps.setInt(5, scout_no);
ps.setString(6, cd_id);
ps.executeUpdate();
// Clean up
ps.close();
}else{
// Create a statement and execute the query on it
ps = c.prepareStatement(updateWithPhoto);
ps.setString(1, surname);
ps.setString(2, firstname);
ps.setDate(3, (java.sql.Date) dob);
File imgfile = new File (photograph);
FileInputStream fis = new FileInputStream(imgfile);
ps.setBinaryStream(4, fis, (int) imgfile.length());
ps.setDate(5, (java.sql.Date) archived);
ps.setInt(6, scout_no);
ps.setString(7, cd_id);
ps.executeUpdate();
// Clean up
ps.close();
}
} catch (SQLException se) {
System.out.println("SQLException in updateYouthMember: " + se.toString());
} catch (Exception e) {
System.out.println("Errors occurred in updateYouthMember: " + e.toString());
}
String updateSectionDetails = ("UPDATE at_section_details " +
"SET sd_section = ?, " +
"sd_pack = ?, " +
"sd_start_date = ?, " +
"sd_end_date = ? " +
"WHERE sd_id = ?;");
try {
// Create a statement and execute the query on it
ps2 = c.prepareStatement(updateSectionDetails);
ps2.setString(1, section);
ps2.setString(2, pack);
ps2.setDate(3, (java.sql.Date) startDate);
ps2.setDate(4, (java.sql.Date) endDate);
ps2.setString(5, sd_id);
ps2.executeUpdate();
// Clean up
ps2.close();
c.close();
} catch (SQLException se) {
System.out.println("SQLException in updateYouthMember - updateSectionDetails: " + se.toString());
} catch (Exception e) {
System.out.println("Errors occurred in updateYouthMember - updateSectionDetails: " + e.toString());
}
} catch (SQLException e1) {
System.out.println("SQLException in updateYouthMember: " + e1.toString());
e1.printStackTrace();
}
finally {
// Ensure connection is closed and returned to the pool, even if errors occur.
// This is *very* important if using a connection pool, because after all the
// connections are used, the application will hang on getConnection(), waiting
// for a connection to become available.
// Any errors from the following closes are just ignored. The main thing is
// that we have definitely closed the connection.
try { if(ps != null) ps.close(); } catch (Exception e) {}
try { if(c != null) c.close(); } catch (Exception e) {}
}
// Done
}
I have already tried:
I found this: bugs.mysql.com/bug.php?id=71084. However, when I use ps.setDate(3, (java.sql.Date) dob, java.util.Calendar.getInstance()); I still get 19/03/1961 when I enter 20/03/1961.
I tried:
// create a calendar Locale locale1 = Locale.UK;
TimeZone tz1 = TimeZone.getTimeZone("UTC+10:00");
Calendar cal1 = Calendar.getInstance(tz1, locale1);
ps.setDate(3, (java.sql.Date) dob, cal1);
and this did not work.
I also tried TimeZone tz1 = TimeZone.getTimeZone("AEST"); which did not work either.
I then tried ps.setString(3, dob.toString()); which causes a Errors occurred in updateYouthMember: java.lang.NullPointerException.
Any help greatly appreciated.
This looks like a time zone issue. Here are a few pointers:
If you are storing the date as a String, you may want to process it as a String in GWT as well. It will save you from trouble when converting from Long to a date.
If you prefer to use getTime() to get the date, try to adjust this number to a midnight (see my answer to this question: how to create a Java Date object of midnight today and midnight tomorrow?)
GWT returns a point of time that is noon instead of midnight. It may enough to push the date one day back for some combination of dates and time zones.
This may not be enough, though - you may need to adjust the getTime() result by a time zone offset before converting it into a Date object, and then use the same offset the other way when showing the date in your app - the same date starts at a different time in different time zones.
Alternatively, you can use getTime() to get time in milliseconds, store it as time in milliseconds, and then use it as time in milliseconds as well when displaying the date. This works for things like timestamps and the like, where the time zone is irrelevant. If time zone is important, you will have to remember in which time zone to display the date - it may be the correct date in some time zones and 1 day off in the other.
I would recommend the latter two approaches only if you need exact time adjusted for a user's time zone somewhere in your app. If you only need dates, strings is a simpler solution.

Cant get records between two dates

My problem is that I can't fetch all records that are between two dates.
I have two JDateChoosers. When I select two dates like '10-apr-2011' to '20-apr-2011' I want all the records between those dates to be displayed in my JList. But I can't get any results in the JList.
I am using mysql database.
private void Display(java.awt.event.ActionEvent evt) {
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=
(Connection)DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test","root","ubuntu123");
java.util.Date jd = jDateChooser1.getDate();
java.util.Date jd1 = jDateChooser2.getDate();
// PreparedStatement stmt = (PreparedStatement) con.prepareStatement("select date from invoice where date = ?);
// PreparedStatement pstmt = (PreparedStatement) con.prepareStatement("SELECT date FROM invoice WHERE date BETWEEN ' ' AND ' '");
PreparedStatement pstmt = (PreparedStatement) con.prepareStatement("SELECT date FROM invoice WHERE date >= '+jd + ' AND date <= '+jd1 + '");
pstmt.execute();
ResultSet rs = pstmt.getResultSet();
int i =0;
DefaultListModel listModel = new DefaultListModel();
while(rs.next())
{
String [] data;
data = new String[100];
data [i] = rs.getString("date");
jList1.setModel(listModel);
listModel.addElement(data [i]);
i = i+1;
}
}
catch (Exception e)
{
System.out.println("2nd catch " + e);
}
}
Can anyone tell me where my mistake is?
Thanks in advance..
Since this is a PreparedStatement you can try:
PreparedStatement pstmt = (PreparedStatement) con.prepareStatement("SELECT date FROM invoice WHERE date >= ? AND date <= ?");
pstmt.setDate(1,new java.sql.Date(jd.getTime()));
pstmt.setDate(2,new java.sql.Date(jd1.getTime()));
ResultSet rs = pstmt.executeQuery();
You need to take out jList1.setModel(listModel); out of the loop
while(rs.next())
{
String [] data;
data = new String[100];
data [i] = rs.getString("date");
//jList1.setModel(listModel);
listModel.addElement(data [i]);
i = i+1;
}
jList1.setModel(listModel);
You need to alter your query. Something like this:-
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String jdStr = sdf.format(jd);
String jd1Str = sdf.format(jd1);
PreparedStatement pstmt = (PreparedStatement) con.prepareStatement("SELECT date FROM invoice WHERE date >= '" + jdStr + "' AND date <= '" + jd1Str + "'");
Previously, in your query, the 2 parameters, jd & jd1 were not getting append. This change will now append it in the query. The problem was with the jd & jd1 not correctly being appended in the query.
Note:- I've added a SDF so that you could format your date in format needed and append it to the query.
never to create an GUI Objects inside hard and long running JDBC, nor inside try - catch - finally, on exception those Object never will be created
DefaultListModel listModel = new DefaultListModel(); should be created an local variable, and then isn't required to recreate a new XxxListModel on runtime
have to remove all elements from listModel, otherwise new Items will be appended to the end of JList
definition for String [] data; and data = new String[100]; and data [i] = rs.getString("date"); inside while(rs.next()) { are quite useless, because database records are stored from this array in XxxListModel, and accessible for other usage for elsewhere
Connection, PreparedStatement and ResultSet should be closed in finally block (try - catch - finally), otheriwe these Objects stays (and increasing) in JVM memory,
are you sure dates in SQL and date from java.util.Date are in the same format?
Try using
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(todaysDate);
to check whenever they are same.
jd and jd1 by default would differ by SQL date #see SQL Dates
This is not the correct way of using PreparedStatement, which is already prepared to handle Dates, so you should not covert them to String. Your code should look like this:
PreparedStatement pstmt = ...
pstmt.setDate(...)
Also your query String is not really using the jd as a variable, you misused ' and "

Categories