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.
Related
I'm currently working on a project where we have an inventory for an optical lens company which is stored in a database. I've connected my database to my java program and im just having an issue selecting a row based on a column value. Im doing this by
String name=lookUpName.getText();
try (
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/productitem?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC",
"root", "123456789"); // for MySQL only
Statement stmt = conn.createStatement();
) {
String strSelect = "select * from products where productName= "+name+"";
System.out.println("The SQL statement is: " + strSelect + "\n"); // Echo For debugging
ResultSet rset = stmt.executeQuery(strSelect);
}
rset.close();
when it tries to execute the query it gives me an error. but if i run a regular query using the sql console like select *
from products where productName='golden vintage'; it works. can someone help me with the java part.
the debugging output i have in there shows
The SQL statement is: select * from products where productName= golden vintage
The error I get is:
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'vintage' at line 1
I figured it out using the Prepared Statements
String strSelect = "select * from products where productName= ?";
PreparedStatement st = conn.prepareStatement(strSelect);
st.setString(1,name);
ResultSet rs = st.executeQuery();
while (rs.next()) {
String productid = rs.getString(1);
String productColors=rs.getString(2);
String productPrices = rs.getString(3);
String productBrands=rs.getString(4);
String productStyles = rs.getString(5);
String productNames=rs.getString(6);
System.out.println(productid +" "+productNames + " " +productBrands + " " + productStyles + " " + productColors + " " + productPrices);
}
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 used the sum function to calculate the total and then save it in another table. When i run this on mysql, it provides the right result. But when included in the jsp, it ends in java.lang.NullPointerException
You can see the same query working in mysql here
The error generated on running the code
rst = stmt.executeQuery("SELECT *
FROM invoicename
ORDER BY name DESC
LIMIT 1;");
if (rst.next()) {
String str = rst.getString("name");
rst1 = stmt.executeQuery("SELECT sum(price)
FROM invoices
WHERE invoicename='" + str + "';");
if (rst1.next()) {
int s = rst1.getInt(1);
if (rst1.wasNull()) {
s = 0;
}
stmt.executeUpdate("INSERT INTO invoice
VALUES('" + str + "',curdate(),curtime(),'" + s + "')");
}
I am not able to display the last row of my database in jsp. I already tried to print rs.getString(1), but it does not work.
ResultSet rs = st.executeQuery("Select MAX(CustomerID) from Customer");
while(rs.next()){out.print(rs.getString(1));}
I don't know if this is what you want but if you are trying to get the whole row there are some ways to accomplish that
ResultSet rs = st.executeQuery("select max(customerid) as id from customer");
rs.next();
String id = rs.getString("id");
rs = st.executeQuery("select field_a, field_b from customer where customerid = " + id);
rs.next();
String row = id + "," + rs.getString("field_a") + "," + rs.getString("field_b");
out.println(row);
Of course you need to replace the field_a and field_b columns with the ones in your customer table and add or remove columns according to your needs.
The shorter way is using order by and limit keywords like this
ResultSet rs = st.executeQuery("select customerid, field_a, field_b from customer order by customerid desc limit 1");
rs.next();
String row = rs.getString("customerid") + "," + rs.getString("field_a") + "," + rs.getString("field_b");
out.println(row);
Be secure of add a primary key or unique constraint to the customerid column for improve the performance of the both methods.
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;
}