BETWEEN query using JDBC with MySQL - mysql

public int getdata(String startDate, String endDate) {
PreparedStatement ps;
int id = 0;
try {
/*
* SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
* java.util.Date startDat = formatter.parse(startDate);
* java.util.Date endDat = formatter.parse(endDate);
*/
// ps = connection.prepareStatement("select * from project.order Where PO_Date Between " + startDate + "' AND '" + endDate + "'");
//ps = connection.prepareStatement("select * from project.order where PO_Date between ? AND DATE_ADD( ?, INTERVAL 1 DAY) ");
//ps = connection.prepareStatement("SELECT * FROM project.order WHERE PO_Date between ? AND ?");
ps = connection.prepareStatement("SELECT * FROM project.order WHERE PO_Date >= ? AND PO_Date <= ?");
//ps = connection.prepareStatement("SELECT * FROM project.order WHERE PO_Date(now())>= ? AND PO_Date(now())<=?");
/*
* ps.setDate(1, new java.sql.Date(startDate)); ps.setDate(2, new
* java.sql.Date(endDate.getTime()));
*/
ps.setString(1, startDate);
ps.setString(2, endDate);
ResultSet rs = ps.executeQuery();
// System.out.println("value of rs "+rs);
while (rs.next()) {
ArrayList<String> arrlist = new ArrayList<String>();
System.out.println(rs.getString(2));
System.out.println(rs.getInt(1));
System.out.println(rs.getString(4));
System.out.println(rs.getString(5));
System.out.println(rs.getString(6));
System.out.println("***************");
// System.out.print(rs.getDate("endDate"));
Iterator<String> itr = arrlist.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
rs.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return id;
}
}
I tried to solve but I am getting out except last date means endDate which we give as a input.
I tried around 5 different queries but still I am getting the same.

In MySQL, the DATE type maps to the Java class java.sql.Timestamp. So you should be working with this type to build your query, and not java.util.Date. Here is code which generates the two timestamps you will need:
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date startDate = formatter.parse(startDate);
java.util.Date endDate = formatter.parse(endDate);
java.sql.Timestamp start = new Timestamp(startDate.getTime());
java.sql.Timestamp end = new Timestamp(endDate.getTime());
Then use your first BETWEEN query to get your result:
PreparedStatement ps = con.prepareStatement("SELECT * FROM project.order
WHERE PO_Date BETWEEN ? AND ?");
ps.setTimestamp(1, start);
ps.setTimestamp(2, end)
Note here that I am using a parametrized PreparedStatement, which avoids (or at least greatly lessens) the possibility of SQL injection.

Try this
SELECT * FROM project.order po
WHERE po.PO_Date IS NOT NULL
AND TO_DATE(PO_Date, 'DD/MM/RRRR') >=
TO_DATE('17/02/2015', 'DD/MM/RRRR')
AND TO_DATE(PO_Date, 'DD/MM/RRRR') <=
TO_DATE('20/06/2015', 'DD/MM/RRRR');

Related

" check if Table is exist or not in database " is not working

I am trying to make a java program can call a table by its name... but the problem is I couldnt figure out how to check if the table is exist or not in database... I am using phpmyadmin data base and here is my code if there is someone can help me ...
enter image description here
public boolean istableNameexist(String un){
boolean uexist = false;
Connection con = myConnection.getconnection();
PreparedStatement ps;
ResultSet rs;
try {
ps = con.prepareStatement("SELECT * FROM `javacontactapp` WHERE TABLE_NAME = ?");
ps.setString(1,name.getText());
rs = ps.executeQuery();
if (rs.next()){
uexist = true;
}
} catch (Exception e) {
System.out.println("wrong");
}
return uexist;
}
public void openfatura(ActionEvent actionEvent) {
String ff1 = name.getText();
Connection con = myConnection.getconnection();
if (!name.getText().isEmpty()) {
if (istableNameexist(name.getText())){
try {
PreparedStatement ps = con.prepareStatement("SELECT `dafat`, `sinif` ,`number` , `price`, `type`, `total` FROM " + ff1 + " WHERE `id` = 1");
ResultSet resultset = ps.executeQuery();

My prepared statement not specified

I am doing a query to the database prepared statement but its just not coming out right.
i get this error when I print my statement.
com.mysql.jdbc.JDBC42PreparedStatement#157b62f9: SELECT * FROM 2015-wind WHERE TimeStamp BETWEEN '2015-01-01' AND '2015-01-25' AND ConnectingArea IN (** NOT SPECIFIED **)
10YAT-APG--L (I print my string and it give me an output).
Anybody knows whats going on here ?
public List<Wind2015> getResultsWind(String beginDate1, String endDate1, String[] connectingAreas1) throws Exception{
int count = 0;
List<Wind2015> myWind2015s = new ArrayList<>();
SimpleDateFormat readFormat = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy",
Locale.ENGLISH);
Date date2 = readFormat.parse(beginDate1);
Date date3 = readFormat.parse(endDate1);
String beginDate = new SimpleDateFormat("yyyy-MM-dd").format(date2);
String endDate = new SimpleDateFormat("yyyy-MM-dd").format(date3);
ArrayList<String> connectingArea = new ArrayList<>(Arrays.asList(connectingAreas1));
StringBuilder inputs = new StringBuilder();
for (int i = 0; i < connectingArea.size(); i++) {
if (i < connectingArea.size()-1) {
inputs.append("?,");
} else {
inputs.append("?");
}
}
String connectingAreaInputs = inputs.toString();
Connection connection = null;
PreparedStatement prepareStatement = null;
ResultSet myRs = null;
System.out.println(connectingAreaInputs);
try {
connection = getConnection();
String sql = "SELECT * FROM `2015-wind` WHERE `TimeStamp` BETWEEN ? AND ? AND `ConnectingArea` IN ("+ connectingAreaInputs +")";
prepareStatement = connection.prepareStatement(sql);
prepareStatement.setString(count+=1,beginDate);
prepareStatement.setString(count+=1, endDate);
System.out.println(prepareStatement);
for (String string : connectingArea) {
System.out.println(string);
count+=1;
prepareStatement.setString(count, string);
}
myRs = prepareStatement.executeQuery();
Wind2015 wind2015 = null;
while (myRs.next()) {
String timeStamp = myRs.getString("Timestamp");
String connectingArea1 = myRs.getString("ConnectingArea");
String value = myRs.getString("ActualWindEnergy");
wind2015 = new Wind2015(timeStamp, value, connectingArea1);
myWind2015s.add(wind2015);
}
return myWind2015s;
} finally {
close(connection, prepareStatement, myRs);
}
}
You're printing the prepared statement with this line:
System.out.println(prepareStatement);
before you assign value(s) to the dynamic placeholders in the IN (...) expression, so they're (correctly) displaying as "not [yet] specified".
Move the print statement to after the for loop that it currently sits before.

how to select data from a database by using a variable?

I have a SQL Server 2008 database and I want to select data by using a String variable... here is the selection code in java:
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:DDS_DSN");
Statement st = con.createStatement();
ResultSet rs;
rs = st.executeQuery("SELECT source_port FROM request_dns WHERE destination_port = 53");
while ( rs.next() ) {
String source_port = rs.getString("source_port");
System.out.println(source_port);
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
I want to make it like this:
String x = "53";
try
{
.
.
rs = st.executeQuery("SELECT source_port FROM request_dns WHERE destination_port = x");
.
.
}
could you please tell me how to do that?...
Thank you
Kind Regards
You want a parameterized query, like this:
int x = 53;
PreparedStatement ps = con.prepareStatement(
"SELECT source_port FROM request_dns " +
"WHERE destination_port = ?");
ps.setInt(1, x);
ResultSet rs = ps.executeQuery();

how to insert "between yyyy-mm-dd and yyyy-mm-dd" into a prepared statement?

I am trying to return a tuples within a certain year and I can't get the prepared statement to return anything but an empty set. Here is the parameter I call it with: year.valueOf("2014-01-01"); not sure if that's already the problem, and this is just for testing it's normally a value from a textfield.
public List<Sales> findYear(Date date) {
try {
List<Sales> listSales = new ArrayList<>();
I tried it with two parameters so this is just the test version.
When I hard code both dates into the prepared statement it works, so the method itself seems fine. Adding ' ' around the ? makes no difference.
PreparedStatement ps = ConnectDB
.getConnection()
.prepareStatement(
"select * from sales where sale_date between ? and '2014-12-30'");
ps.setDate(1, date);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Sales s = new Sales();
s.setEmpno(rs.getInt("empno"));
s.setOutno(rs.getInt("outno"));
s.setPno(rs.getInt("pno"));
s.setCno(rs.getInt("cno"));
s.setOno(rs.getInt("ono"));
s.setQty(rs.getInt("qty"));
s.setSale_date(rs.getDate("sale_date"));
s.setSale_time(rs.getTime("sale_time"));
listSales.add(s);
}
return listSales;
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}
"select * from sales where sale_date between ?-?-? and ?-?-?"
Then set the dates:
prepare.setInt(1, day1);
prepare.setInt(2, month1);
prepare.setInt(3, year1);
prepare.setInt(4, day2);
prepare.setInt(5, month2);
prepare.setInt(6, year3);
You can also turn a date into a string:
"select * from sales where sale_date between ? and ?"
...
String date1Str = SimpleDateFormat("dd-MM-yyyy").format(date1);
String date2Str = SimpleDateFormat("dd-MM-yyyy").format(date2);
prepare.setString(1, date1Str);
prepare.setString(2, date2Str);
Expanded example:
try {
PreparedStatement ps = ConnectDB.getConnection()
.prepareStatement(
"select * from sales where sale_date between ? and ?");
ps.setDate(1, date);
// whatever date2 is
ps.setDate(2, date2);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Sales s = new Sales();
s.setEmpno(rs.getInt("empno"));
s.setOutno(rs.getInt("outno"));
s.setPno(rs.getInt("pno"));
s.setCno(rs.getInt("cno"));
s.setOno(rs.getInt("ono"));
s.setQty(rs.getInt("qty"));
s.setSale_date(rs.getDate("sale_date"));
s.setSale_time(rs.getTime("sale_time"));
listSales.add(s);
}
return listSales;
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}

SQL searching daily attributes error

I am trying to build an application which searches all attributes step by step daily and monthly using the between statement. The daily queries run, but monthly dones't run.
The code:
if (libs.conn.con.State == ConnectionState.Closed) libs.conn.baglanti.Open();
string today = "select getdate()";
SqlCommand today1 = new SqlCommand(today, libs.conn.con);
string today2 = today1.ExecuteScalar().ToString();
string[] day = today2.Split(' ');
day[0] += " 00:00:00";
string dayy = (DateTime.Now.Day).ToString();
string month = (DateTime.Now.Month).ToString();
string year = (DateTime.Now.Year).ToString();
string[] combine = new string[] { "1." };
combine[0] += month + ".";
combine[0] += year + " ";
combine[0] += "00:00:00";
string totalmonth = "(SELECT SUM(para) FROM statistics where datee between '"+combine[0]+"' AND '"+today2+"')";
SqlCommand totalmoneymonthlyquery = new SqlCommand(totalmoneymonth, libs.conn.baglanti);
string totalmoneymonthlyresult = totalmoneymonthlyquery.ExecuteScalar().ToString();
textBox7.Text = totalmoneymonthlyresult.ToString();
use
combine[0]=today2
use first
you may get parameter error to pull data.
String.Format("{0:d/M/yyyy HH:mm:ss}", dt);
String.Format("{0:d/M/yyyy HH:mm:ss}", dt);