Shown JTable from Database with calculate formula - java

I want to shown a JTable with Value from database, but in some coloumn that calculate with a formulation. for excample like this :
Table in database :
from that table i want to shown in JTable, with calculation :
coloumn Pendidikan and Skripsi, value is direct from database.
column Penelitian and MK, value from database calculate with formula value in row minus average from that coloumn. the result shown in table:
so, how to make it like that?, but the formula building in java

this my code to show data to JTable:
tabModel = new DefaultTableModel(null,header);
tabel.setModel(tabModel);
try { String query = "SELECT NIP,Pendidikan,Penelitian,MK,Skripsi FROM table1 group by NIP";
java.sql.Statement Stat = Connect.createStatement();
java.sql.ResultSet rs = Stat.executeQuery(query);
while (rs.next()) {
String nip = rs.getString("NIP");
String bidang = rs.getString("Bidang");
String pendidikan = rs.getString("Pendidikan");
String penelitian = rs.getString("Penelitian");
String mk = rs.getString("MK");
String skripsi = rs.getString("Skripsi");
String[] dataTampil = {nip,bidang,pendidikan,penelitian,mk,skripsi};
tabModel.addRow(dataTampil);
tabel.setModel(tabModel);
}
}catch(Exception e){}
}
but, i can't calculate the table with differnt formula for every coloumn.
for coloumn Pendidikan and skripsi the value direct from database, but for coloumn Penelitian and MK the value form Value in Row minus Average for thats coloumn.

You should first be using rs.getInt() since as your sample shows in your original question, that they are in fact integers. Once you have them as Integers you can do whatever calculations you need to for Penelitian and MK instead of using the ones from the database. In other words, for these two variables, set them to whatever calculation they should be instead of just using the value from rs.getInt()

Related

Retrieve and update field java

Using Java I want to obtain all IDs from my database and select GW_STATUS if it is equal to 0. I used the following SQL statement to achieve this.
PreparedStatement get_id = con.prepareStatement("SELECT ID from SF_MESSAGES where GW_STATUS = 0");
Once the IDs have been obtained, I want to update GW_STATUS to 1 according to their ID as demonstrated in the code below but only one field is being updated when I execute the code.
PreparedStatement update = con.prepareStatement("update SF_MESSAGES set GW_STATUS=? where ID = ?");
update.setInt(1,1);
ResultSet x = get_id.executeQuery();
while(x.next()){
int uber = x.getInt(1);
int array[] = new int[] {uber};
for (int value : array) {
System.out.println("Value = " + value); //Successfully obtains and prints each ID from the databse table
update.setInt(2,value); // Only one ID is updated therefore only field updated
}
}
int result = update.executeUpdate();
System.out.println(result + " Records updated");
I've tried using another update statement within the for loop to update every ID obtained but that doesn't work too. How can I successfully update every field according to their ID?
You can make the whole processing much simple. It turns out that you just want to update SF_MESSAGES which have GW_STATUS equals to 0, so your query can look like the following:
update SF_MESSAGES set GW_STATUS=1 where GW_STATUS=0
Therefore, you do not have to fetch IDs, loop over them so it is more efficient solution.

Java/MySQL - How to retrieve data from specific row

I really can't find a solution for this problem:
Here I have two ResultSets, one which always shows me the number of items stored in my database and one that retrieves all the data from it.
I would like to generate a random number and then generate a random item based on the row number/id in my database. Since I'm fairly new I'm not sure if this is an efficient approach. It doesn't look very clean to retrieve all the data and then iterate over it every time. Especially if I had like 1000 items and the randomly generated number is 999.
PreparedStatement randomSelection = con.prepareStatement("SELECT * FROM items ORDER BY RAND() LIMIT 1"); {
String name = ((ResultSet) randomSelection).getString(2);
System.out.println(name);
}
Tried calling the column itemname with the last line. However I just can't look for a good solution for this problem. Would highly appreciate any help since I'm fairly new to databases.
Thank you
EDIT: This is what I tried now and there is no output somehow
Same for
ResultSet numberOfItemsInDataBase = stmt.executeQuery("SELECT count(*) FROM items;");
// this will return a number between 0 and the number of rows - 1
int id = new Random().nextInt(numberOfItemsInDataBase.getInt(1));
ResultSet itemsInDataBase = stmt.executeQuery("select * from items order by id limit 1 offset " + id);
if (itemsInDataBase.next()) {
String item = itemsInDataBase.getString(2);
System.out.println(item);
}
If you just need a random row of the table then you can do it with plain SQL with the function RAND():
ResultSet itemsInDataBase = stmt.executeQuery("select * from items order by rand() limit 1");
if (itemsInDataBase.next()) {
item = new Item(itemsInDataBase.getString(2));
}
If you want to use the generated random number, then use it in the OFFSET clause of the sql statement:
ResultSet numberOfItemsInDataBase = stmt.executeQuery("SELECT count(*) FROM items;");
// the above query will return exactly 1 row
numberOfItemsInDataBase.next();
// this will return a number between 0 and the number of rows - 1
int id = new Random().nextInt(numberOfItemsInDataBase.getInt(1));
ResultSet itemsInDataBase = stmt.executeQuery("select * from items order by id limit 1 offset " + id);
if (itemsInDataBase.next()) {
item = new Item(itemsInDataBase.getString(2));
}
Use ORDER BY RAND() and limit the result to 1. This circumvents you having to query for the count and then ultimately iterate through the ResultSet until you find the random entry.
try (ResultSet randomSelection = connection
.preparedStatement("SELECT * FROM items ORDER BY RAND() LIMIT 1")) {
if (randomSelection.next()) {
String name = randomSelection.getString(2);
}
}
You can use the limit function to get the item.
The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).
With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1). So in your case the offset can be the the random generated id minus one and maximum number of rows is 1:
select * from items LIMIT {id-1},1; # Retrieve row (id-1)

Insert checkbox in DefaultTableModel using database data

I'm using DefaultTableModel in NetBeans in showing my records from MySQL database. My data is able to display, but what I want is that to display a checkbox column at the end of my table.
I understand it needs to be overridden, but I don't know how and where to start. I see tons of example from the internet but they are using static string data, not from database. Until now I still don't get it. A help will be much appreciated.
Below is my sample code.
try {
conn = DatabaseConnect.connect();
ps = conn.prepareStatement("SELECT productID, name, quantity, price, checked FROM tbl_inventory");
rs = ps.executeQuery();
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
} catch(SQLException ex) {
}
jTable2 is able to display my records from tbl_inventory. The "checked" column from my database table tbl_inventory has default boolean value of 0. But I don't know how to display it as checkbox in my JTtable.
The "checked" column from my database table tbl_inventory has default boolean value of 0. But I don't know how to display it as checkbox in my JTtable.
The easiest way is to convert the "checked" data to a Boolean value as you create the TableModel. Then the default renderer/editor will be used.
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
This means you can't use the above method. You need to copy the data yourself and do the conversion on the checked column.
Check out Table From DataBase. The last example Table From Database Example shows how to copy the data without any conversion.
You will need to modify the code with something like:
while (rs.next())
{
Vector<Object> row = new Vector<Object>(columns);
for (int i = 1; i <= columns; i++)
{
if (i == ?) // convert checked column
{
int value = rs.getInt(i);
row.addElement( value == 0 ? Boolean.FALSE : Boolean.TRUE );
}
else
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}

Generate a new table using Java/SQL Based on values

I am using Java in combination with SQL, as well as Oracle Database to retrieve contents from a spreadsheet I uploaded. If I have a column with the name of each student, and I have a column with their average, and wanted to get the average of the whole class for example, then check if an individual student's average is greater than the class average and put those students who meet those standards on a separate table, how would I go about doing that? I have an idea, but I'm not sure whether this is correct or not. Correct me if I'm wrong.
//Select student averages so I can get each student's individual score
resultset = st.executeQuery("SELECT Student_Averages FROM table");
//Get the class average
stavg = "SELECT Avg(Student_Averages)) AS classAverage FROM table";
rs = st.executeQuery(stavg);
//Iterate through their individual scores and store them in a float variable to
//compare them later.
while(resultset.next()){
float studentaverage = resultset.getFloat("Student_Averages");
}
//Store the class average in a float variable
float classaverage = stavg.getFloat("Student_Averages");
//Compare the individual student average to the class average
if(studentaverage >= classaverage){
//Generate new table with student names
}
I am new at working with databases. I am not sure how to generate a new table with the names of those students who meet the requirement. I would appreciate any help!
First, move this decleration outside the loop
while(resultset.next()){
float studentaverage = resultset.getFloat("Student_Averages");
}
Second, since you did
stavg = "SELECT Avg(Student_Averages)) AS classAverage FROM table";
You should change
float classaverage = stavg.getFloat("Student_Averages");
To
float classaverage = stavg.getFloat("classAverage");
Finally to your question: use this to creat the table
st.executeUpdate("CREATE TABLE IF NOT EXISTS tableName (id INT , studentName VARCHAR(SIZE))");
Then use this to insert the data to the table
String insert = String.format("INSERT INTO tableName("id","studentName") VALUES ('%s','%s)" , idOfStudent someStudentName);
st.execute(intsert);

Count number of rows retrieved from mysql database

public int countBookings() throws SQLException{
ResultSet rs=null;
PMDBController db=new PMDBController();
int rowCount=0;
db.getConnection();
String dbQuery="SELECT COUNT(User) AS UserCount FROM INSTRUCTORBOOKING WHERE USER ='"+instructorId+"'";
rs=db.readRequest(dbQuery);
try{
if(rs.next()){
instructorId=rs.getString("UserCount");
}
}catch(Exception e){
e.printStackTrace();
}
rs.last();
rowCount=rs.getRow();
db.terminate();
return rowCount;
}
Basically what this method is supposed to do is count the number of rows gotten from the database. However, it always returns 1 no matter what is inside. Help!
It seems you have a problem in your query. Since you only select 1 user you will always get a count of 1.
"SELECT COUNT(User) AS UserCount FROM INSTRUCTORBOOKING WHERE USER ='"+instructorId+"'"
Try removing your WHERE clause? Maybe that's not exactly what you want, but we can't see your data model from just one query.
rowCount = rs.getInt("UserCount"); instead of instructorId = rs.getString("UserCount"); would do the trick. Or in other words --- you read the number of rows but into variable instructorId.
The number of rows will always be 1. It's the count i.e. the value of that row you need to look at as your query is designed to return the count of rows and not the actual rows.
SELECT COUNT(User) AS UserCount FROM INSTRUCTORBOOKING WHERE USER ='"+instructorId+"'"
You have wrongly interpreted that the number of rows would be the count you are looking for.

Categories

Resources