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.
Related
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.
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();
Please tell me how to solve the error from the code. I want to get the details from the ms access table. I have used data and description as columns. date is the primary key in ms access. so please let me help me with reading the data from ms access table.
try{
connect();
stmt = (Statement) conn.createStatement();
String sql, ks = " ";
ks = JOptionPane.showInputDialog("enter the date of which you want to read");
String jk = " where date=" + ks;
sql = "SELECT [date],[description] FROM Table2" + jk;
System.out.println("1");
rs = ((java.sql.Statement) stmt).executeQuery(sql);
if(rs.next())
{
String date1="hello",description1="hii";
date1 = rs.getString("date");
description1=rs.getString("description");
JOptionPane.showMessageDialog(null,"Date:"+date1+"\n"+description1);
}
else
{
JOptionPane.showMessageDialog(null,"Sorry the record does not exist");
try
{
close();
}
catch(Exception ea)
{
JOptionPane.showMessageDialog(null, "Error:"+ea.getMessage());
}
}
}
catch(Exception ew)
{
JOptionPane.showMessageDialog(null, "Unable to fetch Data");
JOptionPane.showMessageDialog(null,""+ew.getMessage());
System.out.println(""+ew);
}
Thanks
Your error message says that there is a syntax error in your SQL query. In your example, it seems to be:
SELECT [date],[description] FROM Table2 where date=19apr2015.
This is wrong as the date (19apr2015) does not have the correct format.
A correct SQL query would be:
SELECT [date],[description] FROM Table2 where date=#4/19/2015#
So you will have to parse the user input and convert it into the correct form, or request the user to enter the date in the correct form.
SQL injection
In both cases it is adviced to use a PreparedStatement with the date as parameter instead of putting together the SQL statement using string concatenation, as the latter is dangerous because of an evil thing called SQL injection! For example, imagine, the user wants to do any harm and instead of entering a valid date, he/she enters
#1/1/2000#; DELETE * FROM Table2
So the following SQL statement would be executed by your database:
SELECT [date],[description] FROM Table2 where date=#1/1/2000#; DELETE * FROM Table2
The second statement would simple delete all your data! (To be exact, the statement above would fail as MS Access does not support to chain multiple statements, but other database systems do support this, so this is a security leak that is sleeping until you migrate your database. Apart from that, there are other ways to do SQL injection in MS Access, e.g. by using Subqueries.)
By using a PreparedStatement you can avoid this issue. Apart from that it is more convenient to program:
Date date = /* java.sql.Date-object created from user input */
try (PreparedStatement stmt = conn.prepareStatement(
"SELECT [date],[description] FROM Table2 where date=?")
) {
// set first (and only) parameter value
stmt.setDate(1, date);
// execute statement
try (ResultSet result = stmt.executeQuery()) {
// process result as usual
}
}
i am passing date in sql query using java.Below is my code that retrieve no result.
java.sql.Date d1=java.sql.Date.valueOf(startDate);
java.sql.Date d2=java.sql.Date.valueOf(enddate);
String url= "jdbc:jtds:sqlserver://"+serverName+"/"+database;;
String driver = "net.sourceforge.jtds.jdbc.Driver";
try {
Class.forName(driver);
conn = DriverManager.getConnection(url);
System.out.println("Connected to the database!!! Getting table list...");
Statement sta = conn.createStatement();
String Sql = "Select INDEX from Table where DATE between "+d1+" and "+d2;
System.out.println("sql="+Sql);
rs = sta.executeQuery(Sql);
}
} catch (Exception e) {
e.printStackTrace();}
Query returns no row because date should be passed as '2015-02-28' but query treats date as 2015-02-28 without single quote.Please suggest.
Creating SQL statements by concatenating strings together makes your software vulnerable to SQL injection (if the values of the variables come from user input).
You should use PreparedStatement instead:
PreparedStatement sta =
conn.prepareStatement("Select INDEX from Table where DATE between ? and ?");
sta.setDate(1, d1);
sta.setDate(2, d2);
rs = sta.executeQuery(Sql);
Add single quotes
String Sql = "Select INDEX from Table where DATE between '"+d1+"' and '"+d2+"'";
but the best option would be using PreparedStatement.
Try it like so:
String Sql = "Select INDEX from Table where DATE between '"+d1+"' and '"+d2 + "'";
That being said, you should look into PreparedStatements.
You have multiple issues in the query
INDEX is a reserved word and you need to escape it using backticks http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Date should be used within quotes
So the query should be
String Sql = "Select `INDEX` from Table where DATE between '"+d1+"' and '"+d2+"'";
Replace Your Query with
String Sql = "Select INDEX from Table where DATE between '"+d1+"' and '"+d2+"'";
I suggest you to use PreparedStatement Instead
String query="Select INDEX from Table where DATE between ? and ?";
PreparedStatement ps=con.prepareStatement(query);
ps.setDate(1,d1);
ps.setDate(2,d2);
ps.executeQuery();
I am using ms access DB. I need to obtain sale by date.
Here is my table specification:
BILL_NO DATE SALE
1 8/30/2010 1000
2 8/30/2010 2000
3 8/31/2010 3000
4 8/31/2010 2000
If i want the sale for 8/31/2010 it should return 5000.
I have inserted Date values using java.sql.Date object in DB.
Noted should be that DATE is a reserved keyword in MS Access. You need to specify it with braces. Further, you'd like to use SimpleDateFormat to convert a human readable date string to a fullworthy java.util.Date object which you in turn can construct a java.sql.Date with which in turn can be set in the PreparedStatement the usual way.
Here's a kickoff:
String sql = "SELECT SUM(SALE) as TOTAL_SALE FROM tbl WHERE [DATE] = ? GROUP BY [DATE]";
java.util.Date date = new SimpleDateFormat("MM/dd/yyyy").parse("8/31/2010");
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
int totalSale = 0;
try {
connection = database.getConnection();
statement = connection.prepareStatement(sql);
statement.setDate(new java.sql.Date(date.getTime());
resultSet = statement.executeQuery();
if (resultSet.next()) {
totalSale = resultSet.getInt("TOTAL_SALE");
}
} finally {
close(connection, statement, resultSet);
}
select
sum(SALE) as TOTAL_SALE
from
tbl
where
DATE='8/31/2010'
group by
DATE
Select sum(SALE) from [your table name] where Format([DATE],"mm/dd/yyyy")='08/30/2010';