how can insert date value from jDateChooser to sql database - java

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();

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.

convert java Date to mySql

I'm making a StudentAdministration project with a Usercontroller, studentrepository, some html templates, a css stylesheet and a mySql database. Everything is working out great, and i see my index site, but im having problem creating students because of the Date attribute at my Student class.
In my controller, this is how i create:
#Override
public void create(Student st) {
jdbc.update("INSERT INTO studentdb.student(firstName, lastName,
enrollmentDate, password, cpr)
" + "VALUES('" + st.getFirstName() + "',
'" +
st.getLastName() + "', '" + st.getEnrollmentDate() + "', '" +
st.getPassword() + "', '" + st.getCpr() + "') ");
}
the problem is the st.getEnrollmentDate because it gives me another date format than the 1 MySql accepts. What should i do here? I'd rather not start changing the Date attribute to a String even though that would fix the problem.
You should be using prepared statements with parameter placeholders, and then use setDate. You should not concatenate values into a query string. That leaves you open to SQL injection.
As an example, you need to use:
Connection connection = ..; // defined elsewhere
try (PreparedStatement pstm = connection.prepareStatement(
"INSERT INTO studentdb.student(firstName, lastName, enrollmentDate, password, cpr) " +
" VALUES (?, ?, ?, ?, ?)") {
pstmt.setString(1, st.getFirstName());
pstmt.setString(2, st.getLastName());
// assuming getEnrollmentDate() returns a java.util.Date
pstmt.setDate(3, new java.sql.Date(st.getEnrollmentDate().getTime());
// In a real system you should never store passwords like this!!
pstmt.setString(4, st.getPassword());
// Assuming getCpr() returns string
pstmt.setString(5, st.getCpr());
pstmt.executeUpdate();
}
Note that storing a password like that should never be done. In a real system you would hash the password with something like PBKDF2 or bcrypt.
Try below Steps :-
1.Create a Date object.
Date now = new Date();
2.Create a SimpleDateFormat object by using the constructor,
String pattern = "yyyy-MM-dd";
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
3.Now use the format() method to convert the date object to text format provided in the pattern.
String mysqlDateString = formatter.format(now);

Select value from database with date condition

I have a JComboBox that contains months ( september , july ... )
And one jTable
And a table (Bills) in database that contains ( Id bill , date , products ..)
I want that when a choose a value from jComboBox like september it give me all products in september .
And the date format is like 2014/May/27 14:31:04
and I tried this code but it didnt work because in java i cant use :
String sql1 = "select Products from Bills where Date LIKE "?????+jComboBox1.getSelectedItem()+*" ";
(it give an error and I can't compile)
The code :
try
{
Class.forName(driver).newInstance();
Connection con = (Connection)DriverManager.getConnection(url,user,pass);
String sql1 = "select Products from Bills where Date LIKE "?????+jComboBox1.getSelectedItem()+* " ";
PreparedStatement pst = con.prepareStatement(sql1);
ResultSet rs = (ResultSet) pst.executeQuery(sql1);
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
}
catch( Exception e){
JOptionPane.showMessageDialog(null, e);
}
String sql1 = "select Products from Bills where Date LIKE "?????+jComboBox1.getSelectedItem()+* " ";
Why is like that ?? What are the questions marks?
Should be like that:
String sql1 = "select Products from Bills where Date LIKE '"+jComboBox1.getSelectedItem()+ "'";
You are comparing apples and pears. Dates only can be compared to matching types. So if the column is of type date, you cannot use a String comparison on it (which LIKE actually is).
Your prepared statement should look sorta
...
Date d = new SimpleDateFormat("yyyy/mm/dd hh:mm:ss").parse(jComboBox1.getSelectedItem());
PreparedStatement pst = con.prepareStatement("SELECT PRODUCTS FROM BILLS WHERE DATE = :dv");
pst.setDate("dv", d);
...
Otherwise, You will run into trouble creating invalid SQL or - even worse - make Your software beeing endangered by SQL injection (security issue).
EDIT : Date algorithms always come up with the special flavour of the database vendor. You should check the DB manual for proper operands. For example, DB2 allows inline casting a date without any operand. See SQL query to select dates between two dates for some example.

Database query issue

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());

Prepared statement - using a function as part of the where clause

I am working with a Java prepared statement that gets data from an Oracle database. Due to some performance problems, the query uses a "virtual column" as an index.
The query looks like this:
String status = "processed";
String customerId = 123;
String query = "SELECT DISTINCT trans_id FROM trans WHERE status = " + status + " AND FN_GET_CUST_ID(trans.trans_id) = " + customerId;
Connection conn = getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(query);
ps.execute();
...
} catch (...)
This does not work. Having the function as part of the where clause causes a SQLException. I am aware of CallableStatement, and know I could use that first and then concatenate the results. However, this table uses FN_GET_CUST_ID(trans_id) as part of it's index. Is there a way to use a prepared statement with a database function as a query parameter?
Never concatenate arguments for the SQL into the String. Always use placeholders (?) and setXxx(column, value);.
You'll get the same error if you'd run the SQL in a your favorite DB tool. The problem is that Oracle can't use the function for some reason. What error code do you get?
If Customer ID is numeric keep in int not in String. Then try doing the following:
String query = "SELECT DISTINCT trans_id FROM trans WHERE status = ? AND FN_GET_CUST_ID(trans.trans_id) = ?";
ps = conn.prepareStatement(query);
ps.setString(1, status);
ps.setInt(2, customerId);
ps.execute();
Besides other benefits of prepared statement you won't have to remember about string quotations (this causes your error most likely) and escaping of the special characters.
At the first glance, the query seems to be incorrect. You are missing an apostrophe before and after the usage of status variable (assuming that status is a varchar column).
String query = "SELECT DISTINCT trans_id FROM trans
WHERE status = '" + status + "' AND FN_GET_CUST_ID(trans.trans_id) = " + customerId;
EDIT: I am not from java background. However, as #Aron has said, it is better to use placeholders & then use some method to set values for parameters to avoid SQL Injection.

Categories