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);
Related
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)
i'm working at my uni project and i have to make a classbook for a local school.My problem is that i want to insert multiple grades into the grades field.I've tought about making an integer array of the jtestfield.getText() and then converting it to a string so i can insert it into table.
PreparedStatement ps = con.prepareStatement(
"UPDATE elev SET fizica=? WHERE nume=? AND prenume=?");
// nota1=Integer.parseInt(nota.getText());
// ps.setInt(1, nota1);
String sir=nota.getText();
int[] result = Arrays.stream(sir.split(","))
.mapToInt(Integer::parseInt).toArray();
String note=Arrays.toString(result).replaceAll("\\[|\\]|,|\\s", "");
ps.setString(1,note);
ps.setString(2,text.getText());
ps.setString(3, text1.getText());
ps.executeUpdate();
This is the portion of the code but i keep getting java.lang.NullPointerException.
I've tought about making an integer array...
Don't.
The simplest solution is to use a 1:n relationship between the table elev and a new one score. Then you can store many scores in the second table.
I've been trying to loop through my resultSet but for some reason only the last object in my database is selected. The idea is that I already pulled my needed Section from my database and I now want to add objects to my secions array list.
e.g. I pulled a Section called "Guitar" with the SectionId 1 from my table Sections and now want to add all objects from my table sectionmitschueler where sectionid = 1 to section 1's arraylist.
resultSet = Persistence.executeQueryStatement(aConnection, "SELECT * "
+ "FROM sectionmitschueler");
while (resultSet.next()) {
for(SectionTO eineSectionTO : eventTO.getSections()) {
if(resultSet.getInt("sectionId") == eineSectionTO.getSectionId())
System.out.println(sectionTO.getSectionId());
sectionTO.getSchueler().add(resultSet.getInt("schuelerId"));
}
}
}
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()
I am working with an Oracle Database and have the following code implemented in java (with an SQL imported library), where I have a group of students, their average, and I flag those students with an average that is higher than one standard deviation away from the mean (by inserting a new column with a "1" in it). Then I count the number of students who meet the criteria and add them to a new table:
try{
Statement stOne, stTwo, stThree, stFour;
String SelectAverage = "SELECT MEAN FROM STUDENTS";
ResultSet rsOne = stOne.executeQuery(SelectAverage);
String TotalAverage = "SELECT Avg(MEAN) AS averages FROM STUDENTS";
ResultSet rsTwo = stTwo.executeQuery(TotalAverage);
String student_stan_dev = "SELECT STDEV(MEAN) AS standardDeviation FROM STUDENTS";
ResultSet rsThree = stThree.executeQuery(student_stan_dev);
int onesdMean = 1;
//Loop Duration_Sec column
while(rsOne.next()){
//Convert values into float values
float allAvgs = rsOne.getFloat("MEAN");
float totalAvg = rsTwo.getFloat("averages");
float StDev = rsThree.getFloat("standardDeviation");
float theSD = allAvgs - (onesdMean * StDev);
}
String flaggedStudents = "ALTER TABLE STUDENTS ADD FlaggedStudents INT";
ResultSet rsFour = stFour.executeUpdate(flaggedStudents);
if(allAvgs >= theSD){
String FlagHint = "INSERT INTO STUDENTS.FlaggedStudents VALUES('1')";
st.executeUpdate(FlagHint);
}
String countInstances = "SELECT STUDENTS.NAME, STUDENTS.FlaggedStudents" +
"COUNT(*)OVER(PARTITION BY STUDENTS) AS cnt FROM STUDENTS";
st.executeQuery(countInstances);
st.executeUpdate("CREATE TABLE IF NOT EXISTS StudentCount" +
"(NAME INT , cnt INT)");
String insertVals = String.format("INSERT INTO StudentCount" +
"(NAME , cnt INT") +
" VALUES ('%s','%s')");
st.execute(insertVals);
My question is, I want to implement a k-means algorithm instead, to cluster students who meet this criteria and separate those who are far from meeting this criteria. I have seen source code for the k-means algorithm, but how would I go about doing that with a database implemented in java/SQL? Would I just add this information to a cluster array? Any help would be appreciated.
If you have only one attribute, choose a different algorithm than k-means.
Clustering algorithms are really only good for multidimensional data.
For one-dimensional data, use kernel density estimation to find local minima to split the data there. This produces much more meaningful splits. And at the same time, 1-dimensional data can be sorted (and sorting is something your SQL database does very well), which makes the problem substantially easier than in multiple dimensions.
Seriously. 1-dimensional data is the prime domain of classic statistics. They have excellent tools for this kind of data, so use them!
Multi-dimensional data, where it gets tricky to accelerate your computations, is where data-mining really shines. Once the problem gets too hard to handle with proper statistics in reasonable time, THEN the heuristic approaches of data mining are attractive. But before that, classic statistics is much more clever and advanced.