I have a mysql table that stores the log of Wireless sensor simulation results. It stores node id of each sensor node, energy of each node and and status of each sensor i.e, whether it is in sending state or recieving state etc. Now I want to create a JTable which displays 5 fileds for each row which are:
NodeId , energy Left, No. Of Packets Sent , No. Of Packets Recieved, No. Of Packets Corrupted.
I am using following queries:
SELECT COUNT(*) FROM node WHERE nodeid='i' AND stetus='sending'
SELECT COUNT(*) FROM node WHERE nodeid='i' AND stetus='corrupted'
SELECT COUNT(*) FROM node WHERE nodeid='i' AND stetus='recieved'
SELECT MIN(energi) FROM node WHERE nodeid='i'
To get Fields for JTable contents.
Below is the Code That I have written: Please help me to resolve this.
I am not able to display JTable.
import java.util.Vector.*;
import java.sql.*;
JFrame f = new JFrame();
f.setSize(800,800);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Connection Db=null;
ResultSet Results,res,rest,re;
String stetus;
Vector data = new Vector();
Vector row = new Vector(50);
JPanel p = new JPanel();
Vector<String> columnNames = new Vector<String>();
double energi,nodeid,en;
String url= "jdbc:mysql://localhost:3306/prowler";
String username="root";
String password = "not telling you";
try {
Class.forName("com.mysql.jdbc.Driver");
Db= DriverManager.getConnection(url,username,password);
}
catch(ClassNotFoundException cnf) {
System.err.println("Unable to load JDBC bridge" + cnf);
System.exit(1);
}
catch(SQLException se) {
System.err.println("Cannot connect to database" + se);
System.exit(2);
}
int num = Integer.parseInt(name.getSelectedText());
for(int i=1;i<=num;i++) {
row.addElement(i);
try {
Statement st = Db.createStatement();
Results = st.executeQuery("SELECT COUNT(*) FROM node WHERE nodeid='i' AND stetus='sending'");
row.addElement(Results.getObject(1));
}
catch(SQLException se) {
System.out.println("Query Not Executed" + se);
}
try {
Statement st = Db.createStatement();
res = st.executeQuery("SELECT COUNT(*) FROM node WHERE nodeid='i' AND stetus='corrupted'");
row.addElement(res.getObject(1));
}
catch(SQLException se) {
System.out.println("Query Not Executed" + se);
}
try {
Statement st = Db.createStatement();
rest = st.executeQuery("SELECT COUNT(*) FROM node WHERE nodeid='i' AND stetus='recieved'");
row.addElement(rest.getObject(1));
}
catch(SQLException se) {
System.out.println("Query Not Executed" + se);
}
try {
Statement st = Db.createStatement();
re = st.executeQuery("SELECT MIN(energi) FROM node WHERE nodeid='i'");
row.addElement(re.getObject(1));
}
catch(SQLException se) {
System.out.println("Query Not Executed" + se);
}
data.addElement(row);
}
columnNames.add("Node Id");
columnNames.add("Packets Sent");
columnNames.add("Packets Corrupted");
columnNames.add("Packets Recieved");
columnNames.add("Energy Left");
JTable table = new JTable(data,columnNames);
JScrollPane jsp = new JScrollPane(table);
p.add(jsp);
f.add(p);
Well if I get you it's fairly simple, something like
Select nodeid,
Count(case stetus when 'sending' then 1 else null end) as Sent,
Count(case stetus when 'received' then 1 else null end) as Received,
Count(case stetus when 'corrupted' then 1 else null end) as Corrupted,
Min(energi) as remaining
From Node Group By NodeId
I think
The case manouver inside count is a sneaky trick. Count(SomeColumnName) will skip nulls, but you can count an expression, so you bash one together, that's null when you don't want it in the count.
Related
I am running a query on ID column but I don't want it to be visible in my frame/pane. How can I achieve this? Shall I make another table, is there a function in sql/mysql which allows to hide columns? I tried to google it but havent found anything yet.
Here is the code:
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int col = e.getColumn();
model = (MyTableModel) e.getSource();
String stulpPav = model.getColumnName(col);
Object data = model.getValueAt(row, col);
Object studId = model.getValueAt(row, 0);
System.out.println("tableChanded works");
try {
new ImportData(stulpPav, data, studId);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
public class ImportData {
Connection connection = TableWithBottomLine.getConnection();
public ImportData(String a, Object b, Object c)
throws ClassNotFoundException, SQLException {
Statement stmt = null;
try {
String stulpPav = a;
String duom = b.toString();
String studId = c.toString();
System.out.println(duom);
connection.setAutoCommit(false);
stmt = connection.createStatement();
stmt.addBatch("update finance.fin set " + stulpPav + " = " + duom
+ " where ID = " + studId + ";");
stmt.executeBatch();
connection.commit();
} catch (BatchUpdateException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null)
stmt.close();
connection.setAutoCommit(true);
System.out.println("Data was imported to database");
}
}
}
public class MyTableModel extends AbstractTableModel{
int rowCount;
Object data [][];
String columnNames [];
public MyTableModel() throws SQLException{
String query ="SELECT ID, tbl_Date as Date, Flat, Mobile, Food, Alcohol, Transport, Outdoor, Pauls_stuff, Income, Stuff FROM finance.fin";
ResultSet rs ;
Connection connection = TableWithBottomLine.getConnection();
Statement stmt = null;
stmt = connection.createStatement();
rs = stmt.executeQuery(query);
rs.last();
rowCount = rs.getRow();
data = new Object[rowCount][11];
rs = stmt.executeQuery(query);
for (int iEil = 0; iEil < rowCount; iEil++){
rs.next();
data[iEil][0] = rs.getInt("ID");
data[iEil][1] = rs.getDate("Date");
data[iEil][2] = rs.getFloat("Flat");
data[iEil][3] = rs.getFloat("Mobile");
data[iEil][4] = rs.getFloat("Food");
data[iEil][5] = rs.getFloat("Alcohol");
data[iEil][6] = rs.getFloat("Transport");
data[iEil][7] = rs.getFloat("Outdoor");
data[iEil][8] = rs.getFloat("Pauls_stuff");
data[iEil][9] = rs.getFloat("Income");
data[iEil][10] = rs.getFloat("Stuff");
}
String[] columnName = {"ID", "Date","Flat","Mobile"
,"Food","Alcohol","Transport", "Outdoor", "Pauls_stuff", "Income", "Stuff"};
columnNames = columnName;
}
This has solved my problem:
table.removeColumn(table.getColumnModel().getColumn(0));
I placed this in my class contructor. This lets remove the column from the view of the table but column 'ID' is still contained in the TableModel. I found that many people looking for an option to exclude specific column (like autoincrement) from SELECT statement in sql / mysql but the language itself doesn't have that feature. So I hope this solution will help others as well.
Don't put ID in the select part of the query
String query ="SELECT tbl_Date as Date, Flat, Mobile, Food, Alcohol, Transport,
Outdoor, Pauls_stuff, Income, Stuff FROM finance.fin";
Hello so i'm trying to code my own type of error catching on a sql statement. On my method add order i want to add some way of stopping someone from selling a product which has no stock. My code below does not yet do that. I can add orders and update the stock amount but i haven't figured out a way of adding an if statement that works.
#FXML
public void AddOrder(ActionEvent event) {
String orderID = orderBox.getText();
String customerID = customerBox.getText();
String productID = productBox.getText();
String amount = amountBox.getText();
// String cost = costBox.getText();
String date = dateBox.getText();
PreparedStatement sample;
dc = new Database();
try {
c = dc.Connect();
sample = c.prepareStatement("Select stockAmount from inventory WHERE productID = ?");
ResultSet rs = sample.executeQuery();
while (rs.next()) {
Integer amount2 = rs.getInt("Amount");
if (amount2 <= 0) {
System.out.println("No stock exists");
} else {
query = c.prepareStatement(
"INSERT INTO ordertable (orderID,customerID,productID,Amount,Date)VALUES(?,?,?,?,?)");
update = c.prepareStatement("UPDATE inventory set stockAmount = stockAmount-? WHERE productID =?");
update.setString(1, amount);
update.setString(2, productID);
update.execute();
query.setString(1, orderID);
query.setString(2, customerID);
query.setString(3, productID);
query.setString(4, amount);
// query.setString(5, cost);
query.setString(5, date);
query.executeUpdate();
// update.executeUpdate();
Alert confirmation = new Alert(Alert.AlertType.CONFIRMATION, "Saved");
// closeConfirmation.showMessageDialog(this, "Saved");
confirmation.show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
orderBox.clear();
customerBox.clear();
productBox.clear();
amountBox.clear();
dateBox.clear();
loadDataFromDatabase(event);
}
Below is the error i'm getting
java.sql.SQLException: No value specified for parameter 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
at
If you are just having trouble because of that exception, check these lines:
sample = c.prepareStatement("Select stockAmount from inventory WHERE productID = ?");
ResultSet rs = sample.executeQuery();
The query is defined to accept a parameter for productID, but you haven't given it a value prior to executing the statement. You'll need to change the query so that it doesn't require a parameter or assign a value to the parameter, like this:
sample = c.prepareStatement("Select stockAmount from inventory WHERE productID = ?");
sample.setString(1, productID);
ResultSet rs = sample.executeQuery();
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;
}
I have a mySQL table named userinfo with colums- userId, userName, Password, city, age- userId is Pkey and Autoincremnt
When a user Login on a login.jsp, he submits username and Pasword.
These two parameters of login.jsp are received in UserLogin servlet and then checked in userinfo Table. If matched, he could log in.
I tried SELECT but I get numerous error. What should be the correct way:-
try {
String sql = "Select UserName, UserPW From SocialNetwork.RegisteredUser";
conn = ConnectionFactory.getConnection();
PreparedStatement ptmt = (PreparedStatement) conn
.prepareStatement(sql);
ptmt.executeQuery();
Statement stmt = (Statement) conn.createStatement();
s = connection.prepareStatement("select id_usuario, id_grupo from usuarios_grupos where id_grupo = ?");
//storing user data in ResultSet
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String refName = rs.getString("UserName");
String refPass = rs.getString("UserPW");
if (user.equals(refName) && pw.equals(refPass) ) {
out.println("<html>");
out.println("<body>");
out.println("You are In");
out.println("</body>");
out.println("</html>");
System.out.println("sucess");
}
}
}catch (SQLException e) {
e.printStackTrace();
}
by using Statement interface you can not dynamically set the values. use PreparedStatement interface for second query.
import package in you class import javas.sql.*;
try {
String sql = "Select UserName, UserPW From SocialNetwork.RegisteredUser UserName = ?";
conn = ConnectionFactory.getConnection();
PreparedStatement ptmt =conn.prepareStatement(sql);
ptmt.setString(1, user)
ResultSet rs= ptmt.executeQuery();
while (rs.next()) {
String refName = rs.getString(1);//field index of user name
String refPass = rs.getString(2);//field index of password
if (user.equals(refName) && pw.equals(refPass) ) {
out.println("<html>");
out.println("<body>");
out.println("You are In");
out.println("</body>");
out.println("</html>");
System.out.println("sucess");
}
}
}catch (SQLException e) {
e.printStackTrace();
}
Are you asking for the entire code listing? in your current code you seem to be executing some queries for no reason, then getting a list of all users and iterating through them looking for a match. Try using a query like
sql ="Select UserName, UserPW From SocialNetwork.RegisteredUser where UserName=?"
ResultSet rs = stmt.executeQuery(sql);
then check the password in code
if(rs.next()){
String refPass = rs.getString("UserPW");
if (pw.equals(refPass) )
}
I have a MySQL database (ver. 5.2 CE) and I have a table which I want to filter into a another table based on the WHERE conditions given by the user (this comes from an array list). I want to perform count query on this new table for a split chosen by the user. For example, COUNT(*) from TableName WHERE [userConditions like gender=male and gender=female, etc]. The user can give more than one WHERE conditions but the COUNT query will only take one condition at a time. Hence, I made my method (which performs this query) an array to return multiple queries based on the number of conditions chosen by the user and then execute each query in a for loop. However, this seems to give me compilation errors in 2 ways: i) the way I return a built string in a String[] method and ii) the way I execute the COUNT query. The code for these problems:
private String countQuery;
public SetupSubsamplePopulation(UserSelectedSplit split) {
this.split = split;
// connect to the database
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull","root", "sharadha_1992");
String buildSelectQuery = buildSelectQueryForCode();
String getRowsFromTable = getNumberOfRows();
stmt = connection.createStatement();
rows = stmt.executeUpdate(buildSelectQuery);
ResultSet rs = stmt.executeQuery(getRowsFromTable);
for (int i=0; i<getCountOfWhereCondition().length; i++){
//where I get the executeQuery error
ResultSet rs1= stmt.execute(getCountOfWhereCondition());
while (rs1.next()){
rowsCount= rs.getRow();
rows_count++;
}
}
while (rs.next()) {
rows = rs.getRow();
rows_inserted++;
}
System.out.println(rows_inserted);
System.out.println(rows_count);
} catch (Exception e) {
e.printStackTrace();
}
}
The method which returns the array of COUNT queries:
public String[] getCountOfWhereCondition() {
countQuery="SELECT COUNT (*) FROM (SELECT * from mygrist_samples.subsample_population WHERE ";
for (int i = 0; i < split.getSplitConditions().size(); i++) {
String getCorrespondingCodeFromDatabase = split.getSplitConditions().get(i).getCode();
getCorrespondingCodeFromDatabase = getCorrespondingCodeFromDatabase.replaceAll("-", "_");
Enumerations enum1 = new Enumerations();
String getCorrespondingRelationshipOperator = enum1.getOperator(split.getSplitConditions().get(i).getRelationship());
countQuery+=getCorrespondingCodeFromDatabase + " " + getCorrespondingRelationshipOperator + " '" + split.getSplitConditions().get(i).getAnswer() + "'";
}
countQuery+=")";
System.out.println(countQuery);
//error which doesn't allow me to return a string
return countQuery;
}
Can someone please tell me how to implement this sensibly? Thank you very much.
I think you want conditional aggregation rather than a where:
select count(*)
from mygrist_samples.subsample_population
WHERE XXX
Is the same as:
select sum(case when XXX then 1 else 0 end) as cnt1
from mygrist_samples.subsample_population
Now you can add multiple conditions on one call:
select sum(case when XXX then 1 else 0 end) as cnt1,
sum(case when yyy then 1 else 0 end) as cnt1
from mygrist_samples.subsample_population