I have two tables stops and arrivaltimes I want to put the right spelling ´mon-fri´ or sat or sun in the query what is the best way to manage that in java? for example today is monday if the stop's name is ABC weekday is Monday and the current time equal 10:43 to the arrivaltime I want to get just the route number 9
This query works fine but I dont know how to get the day spelling in:
SELECT route from arrivaltimes
INNER JOIN stops ON arrivaltimes.stop_id=stops.stop_id
WHERE weekday = "+ day +"
and time_format(arrivaltime,'%H:%i')= time_format(curtime() ,'%H:%i')
and name LIKE stop_name
my code:
Connection con = DriverManager.getConnection(host, user, password);
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_WEEK);
// Create a statement
Statement stt = con.createStatement();
DatabaseMetaData dbm = con.getMetaData();
ResultSet stopsExist = dbm.getTables(null, null, "stops", null);
if (stopsExist.next()) {
// the stops and arrrivaltimes tables exist.
PreparedStatement preparedLatLong = con
.prepareStatement("SELECT lat, longi from stops");
ResultSet rsLatLong = preparedLatLong.executeQuery();
while (rsLatLong.next()) {
double lat_stop = rsLatLong.getDouble("lat");
double lon_stop = rsLatLong.getDouble("longi");
double distStops = haversineDistance(latD, longD, lat_stop,
lon_stop);
if (distStops <= 10) {
String stop_name = rsLatLong.getString("name");
PreparedStatement preparedTime = con
.prepareStatement("SELECT route from arrivaltimes INNER JOIN stops"
+ " ON arrivaltimes.stop_id=stops.stop_id "
+ "WHERE weekday = "+ day +" and time_format(arrivaltime,'%H:%i')= time_format(curtime() ,'%H:%i') and name LIKE"
+ stop_name);
ResultSet rsArrivaletime = preparedTime.executeQuery();
routeList = new ArrayList<Integer>();
while (rsArrivaletime.next()) {
int route = rsArrivaletime.getInt("route");
routeList.add(route);
}
}
break;
}
Related
I am trying to display my data from my database. I am currently doing one query execution at a time to get one particular result for each year. I need to do this for all the columns in my database however this will make the code incredibly messy. Is there an easier way to read the data in from the database to display to a line graph?
Current code snippet:
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
String sql = "SELECT SUM(all_motor_vehicles), Year FROM Vehicle WHERE Year = 2005";
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
amount = Integer.parseInt(rs.getString(1)); //get the result
yearFromDB = rs.getString(2);
System.out.println(amount + " " + yearFromDB); //print result
int amount2006;
String yearFromDB2006;
String sql2 = "SELECT SUM(all_motor_vehicles), Year FROM Vehicle WHERE Year = 2006";
pst = con.prepareStatement(sql2);
rs = pst.executeQuery();
amount2006 = Integer.parseInt(rs.getString(1)); //get the result
yearFromDB2006 = rs.getString(2);
System.out.println(amount2006 + " " + yearFromDB2006); //print result
int amount2007;
String yearFromDB2007;
String sql3 = "SELECT SUM(all_motor_vehicles), Year FROM Vehicle WHERE Year = 2007";
pst = con.prepareStatement(sql3);
rs = pst.executeQuery();
amount2007 = Integer.parseInt(rs.getString(1)); //get the result
yearFromDB2007 = rs.getString(2);
System.out.println(amount2007 + " " + yearFromDB2007); //print result
dataset.addValue(amount, allMotorVehicles, yearFromDB);
dataset.addValue(amount2006, allMotorVehicles, yearFromDB2006);
dataset.addValue(amount2007, allMotorVehicles, yearFromDB2007);
JFreeChart chart = ChartFactory.createLineChart("Traffic by Vehicle type", "Vehicle", `"Amount",dataset);`
Snippet of information in database:
Implementing suggested Query giving SQL Error:
Executing query in DB returns:
I can retrieve the year 2005 using rs.getString(1) and it's corresponding number using rs.getString(2) but when I try to retrieve year 2006 and it's number through rs.getString(3) and rs.getString(4) I get an SQLException Error
String sql = "SELECT Year, SUM(all_motor_vehicles) AS allmotor\n" +
"FROM Vehicle\n"
+ "WHERE Year IN (2005, 2006, 2007)\n"
+ "GROUP BY YEAR;";
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
amount = Integer.parseInt(rs.getString(2)); //retrieves amount
yearFromDB = rs.getString(1);
System.out.println(amount + " " + yearFromDB); //retrieves year (2005)
System.out.println(rs.getString(3) + " " + rs.getString(4)); //gives me an SQL ERROR
You should instead do a single GROUP BY query in which you aggregate sales by year:
SELECT Year, SUM(all_motor_vehicles) AS all_sales
FROM Vehicle
WHERE Year IN (2005, 2006, 2007) -- or whatever years you want in your report
GROUP BY Year;
I won't bother giving you boilerplate JDBC code for the above query, as you seem to already have the basics of that mastered. Note that I give an alias to the SUM(), in case you would want to access the result set in Java using it.
in my project i have created a system to book a room.
My problem concerns the booking of a room on the same date.
This is the DB about reservation.
id_book,login,email,typeroom,numroom,arrivaldate,departuredate.
And this is the code to check if a room is available in a period:
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// out.println("driver loaded");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Hotel?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root" ,"123456789");
out.println("Connect");
Statement st = con.createStatement();
Statement stmt = con.createStatement();
out.println("connection successfull");
String check = ("SELECT res1.id_prenotazione, res1.typeroom, res1.arrivaldate, res1.departuredate\n" +
"FROM reservation res1, reservation res2\n" +
"WHERE ( res1.typeroom = res2.typeroom ) \n" +
"AND (res1.arrivaldate <= res2.departuredate)\n" +
"AND (res2.arrivaldate <= res1.departuredate)");
String check1 = ("SELECT count(*) FROM reservation WHERE arrivaldate");
ResultSet rs2 = stmt.executeQuery(check);
ResultSet rs3 = stmt.executeQuery(check1);
if( rs2 != rs3) {
int rs = st.executeUpdate("insert into reservation (login,email,typeroom,numroom,arrivaldate,departuredate)values ('"+login+"','"+email+"','"+typeroom+"','"+numroom+"','"+arrivaldate+"','"+departuredate+"')");
}
String getResultSet = ("SELECT count(*) FROM reservation WHERE arrivaldate ='"+arrivaldate+"'");
String rs1 = ("SELECT count(*) FROM reservation WHERE arrivaldate");
if (getResultSet != rs1) {
int i=st.executeUpdate("DELETE FROM reservation WHERE id_prenotazione ='"+id_prenotazione+"'");
}
The problem is that in this way I keep recording the same rooms with the same date, how can i solve?
I did not get your question fully. The part that I understood is you obviously don't want to overbook rooms on a given date.
If it is the case, while showing available rooms, you can fire count(*) query for that date. There is no need to any update operation at that time.
It is at the time of actual booking, you need to handle the overbooking either by taking proper lock or writing query in a way that no. of rooms does not go below 0.
The thing i want to achieve here is that i have a table name total_product in mysql database and i want to retrieve the value of SNo = 1 from the table and update the Quantity in the table.
There is a text box i am using in GUI in which the additional product produced will be written.
The output from the table is stored in variable id and the new quantity that is produced is stored in the variable q1.
so the new product quantity will be q1 = q1 + id.
I am not able to understand what should i put in the sql statement that is used in stmt.executeUpdate(sql) because the sql is a string and i have to pass an integer value to Qunty in the sql string.
Please Help.
Connection conn = null ;
Statement stmt = null ;
String url = "jdbc:mysql://localhost:3306/project";
String user = "root";
String password = ".dpadpep";
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url,user,password);
String sql = "Select Qunty from total_product " + "where SNo = 1";
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
int id=0;
int q1 = Integer.parseInt(fld1[0].getText());
while(rs.next()) {
id = rs.getInt(1);
System.out.println("Quantity="+id);
}
q1 = q1+id;
sql = "UPDATE total_product " + "set Qunty = q1 where SNo=1";
stmt.executeUpdate(sql);
You don't need to explicitly retrieve the current value in the database, you can simply add the additional amount directly:
int q1 = Integer.parseInt(fld1[0].getText());
String sql = "UPDATE total_product SET Qunty = Qunty + ? WHERE SNo = 1";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, q1);
ps.executeUpdate();
I'm currently writing a java application which is used to print bar codes out, which the information for is obtained from a MySQL database. The data in SQL has a property which defines which type of bar code it is, value 1 = serialized and 2 = un-serialized. I was wondering how I would use an if statement to set a variable to define what type of bar-code is being used - in java.
On the SQL database the value for bar code type is 'FK_BarcodeTypeID'
The code I have so far is:
String SQL ="SELECT [PK_PrintQueueID]" +
" ,[FK_PrinterID]" +
" ,[FK_BarcodeTypeID]" +
" ,[Barcode]" +
" ,[Quantity]" +
" ,[QueueDate]" +
" ,[ProcessedDate]" +
" FROM [Brad].[dbo].[PrintQueue]" +
" WHERE ProcessedDate IS NULL";
//Declare variable connection.
Connection connection = null;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//get current date time with Date()
Date date = new Date();
// System.out.println(dateFormat.format(date));
//
try {
connection = DriverManager.getConnection(connectionString);
Statement stmt = connection.createStatement();
Statement stmt2 = null;
ResultSet rs = stmt.executeQuery(SQL);
while (rs.next()) {
System.out.println(rs.getString("Barcode"));
// System.out.println(rs.getString("PK_PrintQueueID"));
// System.out.println(rs.getString("ProcessedDate"));
String SQL2 = "UPDATE PrintQueue SET ProcessedDate = '"+dateFormat.format(date)+"' WHERE PK_PrintQueueID = '"+rs.getString("PK_PrintQueueID")+"' ";
// System.out.println(SQL2);
String ZPL = "^XA ^FX BARCODE ^BY4,2,050 ^FO140,40^BC^FD"+rs.getString("Barcode")+"^FS ^XZ";
System.out.println(ZPL);
// THIS IF STATEMENT SETS TYPE OF BARCODE TO
// TYPE 1 OR 2
I tried using the following but had no luck;
String BCSerialized = "SELECT * FROM PrintQueue WHERE FK_BarcodeTypeID = '1'";
System.out.println(BCSerialized);
String BCUnSerialized = "SELECT * FROM PrintQueue WHERE FK_BarcodeTypeID = '2'";
System.out.println(BCUnSerialized);
I am struggling to work out how to do the above, therefore any advice is appriciated.
Thankyou!
I have to check the rooms available during a particular period ie from a starting date to an ending one for a hotel reservation system. To choose a starting and ending date, I used a JCalendar. The problem is that I am getting an error when I am creating the SQL string query and also I don't know how to retrieve the date from the JCalendar to be used in the query.
Below are code snippets of what I have done and where I am stucked.
JCalendar instantiation:
JDateChooser arrival = new JDateChooser();
JDateChooser departure = new JDateChooser();
Query to check for rooms available:
ResultSet rs = null;
Connection conn = null;
Statement stmt = null;
try {
// new com.mysql.jdbc.Driver();
Class.forName("com.mysql.jdbc.Driver").newInstance();
String connectionUrl = "jdbc:mysql://localhost:3306/testing?autoReconnect=true&useSSL=false";
String connectionUser = "root";
String connectionPassword = "admin";
conn = DriverManager.getConnection(connectionUrl, connectionUser,
connectionPassword);
stmt = conn.createStatement();
String query = "select * from testing.room as ro
where ro.room_id not in
(
select re.room_no
from testing.booking as re
where (arrival_date >= "2016-05-24" and departure_date < "2016-05-29")
or (departure_date >= "2016-05-24" and arrival_date < "2016-05-29")
)";
rs = (ResultSet) stmt.executeQuery("");
while (rs.next()) {
System.out.println(rs.getString(1) + " " + rs.getString(2)
+ " " + rs.getString(3)+ " " + rs.getString(4)+ " "+ rs.getString(5));
}
} catch (Exception e) {
e.printStackTrace();
}
I have hardcoded the dates here :
where (arrival_date >= "2016-05-24" and departure_date < "2016-05-29")
or (departure_date >= "2016-05-24" and arrival_date < "2016-05-29")
That's because I don't know how to take the values from the JCalendar to write it there ie should I use PreparedStatements and get the text or something?
And also, I am getting an error with the query ie where I wrote String query= "query" as it says "Insert missing quotes".
You need to make two changes here:
Get the dates from JDateChooser fields (by calling getDate() method on JDateChooser objects).
Use PreparedStatement and set the dates dynamically. Below is an exmple:
JDateChooser arrival = new JDateChooser();
JDateChooser departure = new JDateChooser();
PreparedStatement pStmt = conn.prepareStatement("select * from testing.room where arrival_date >= ? and departure_date < ?");
pStmt.setDate(1, arrival.getDate());
pStmt.setDate(2, departure.getDate());
ResultSet rs = preparedStatement.executeQuery();