In this code:
public static void viewTable(Connection con, String dbName)
throws SQLException {
Statement stmt = null;
String query =
"select COF_NAME, SUP_ID, PRICE, " +
"SALES, TOTAL " +
"from " + dbName + ".COFFEES";
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");
System.out.println(coffeeName + "\t" + supplierID +
"\t" + price + "\t" + sales +
"\t" + total);
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
if (stmt != null) { stmt.close(); }
}
}
In particular, this code:
ResultSet rs = stmt.executeQuery(query);
Does this statement retrieve all rows to ResultSet, or partly? I need to load a table with 5 million rows in Hibernate and there is an OutofMemory error. It fails on this line:
List<Term> terms = em.createQuery(criteria).getResultList();
I need to find a way in Mysql & Hibernate to load this table with a memory issue. Thanks.
Related
In method save() I receive as input an instance of Employee, and I want to add it to the table employee and return this added instance. I read about this problem but I didn't find an answer to my problem.
public Employee save(Employee employee) throws SQLException {
Connection connection = ConnectionSource.instance().createConnection();
String sql = "insert into employee VALUES(" +employee.getId() + ", " + "'employee.getFullName().getFirstName()'" + ", " +"'employee.getFullName().getLastName()'"+ ", " +"'employee.getFullName().getMiddleName()'"+ ", " + "'employee.getPosition()'" + ", " +"'employee.getHired()'"+ ", " + employee.getSalary()+ ", " +employee.getManagerId()+ ", " +employee.getDepartmentId() + ")";
connection.prepareStatement(sql);
PreparedStatement ps2 = connection.prepareStatement("select * from employee");
ResultSet resultSet = ps2.executeQuery();
resultSet.next();
Employee emp = new Employee(... );
return emp;
}
First of all, better not use such approach:
String sql = "insert into employee VALUES(" +employee.getId() + ", " + "'employee.getFullName().getFirstName()'" + ", " +"'employee.getFullName().getLastName()'"+ ", " +"'employee.getFullName().getMiddleName()'"+ ", " + "'employee.getPosition()'" + ", " +"'employee.getHired()'"+ ", " + employee.getSalary()+ ", " +employee.getManagerId()+ ", " +employee.getDepartmentId() + ")";
you can have an sql injection in that case.
Instead use
String sql = "insert into employee values (?, ?, ...)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setInt(1, employee.getId());
statement.setString(2, employee.getFullName().getFirstName());
...
For your problem you can try something like this:
public Employee save(Employee employee) throws SQLException {
try (Connection connection = ConnectionSource.instance().createConnection();;
PreparedStatement statement = connection.prepareStatement(SQL_INSERT,Statement.RETURN_GENERATED_KEYS);) {
statement.setInt(1, employee.getId());
statement.setString(2, employee.getFullName().getFirstName());
// ...
int affectedRows = statement.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating employee failed, no rows affected.");
}
try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
if (generatedKeys.next()) {
employe.setId(generatedKeys.getLong(1));
}
else {
throw new SQLException("Creating employe failed, no ID obtained.");
}
}
return employee;
}
}
Those are the SQL tables I am taking the data from
String sql = "CREATE TABLE IF NOT EXISTS term_index (\n"
+ " term_id integer PRIMARY KEY AUTOINCREMENT ,\n"
+ " term text ,\n"
+ " multiterm integer \n"
+ ");";
execute(sql);
sql = "CREATE TABLE IF NOT EXISTS doc_term (\n"
+ " term_id integer ,\n"
+ " wiki_id text ,\n"
+ " section text ,\n"
+ " freq integer ,\n"
+ " tfidf double ,\n"
+ " cvalue double ,\n"
+ " rake double ,\n"
+ " PRIMARY KEY (term_id, wiki_id, section) \n"
+ ");";
execute(sql);
This is the SQL statement to take the termIDs from the tables above
/**
*
* #param wikiID
* #return
*/
public HashSet<Integer> getWholeDocumentTermIDs(String wikiID) {
HashSet<Integer> termIDs = new HashSet<Integer>();
String sql= "SELECT term_id FROM doc_term WHERE wiki_id = ?";
try {
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1,wikiID);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
String sql2= "SELECT term_id, multiterm FROM term_index WHERE term_id = ?";
PreparedStatement stmt2 = conn.prepareStatement(sql2);
//System.out.println(rs.getInt("term_id"));
int term_id = rs.getInt("term_id");
if(term_id != 0) {
stmt2.setInt(1,term_id);
ResultSet rs2 = stmt2.executeQuery();
int multiterm = rs2.getInt("multiterm");
if(multiterm == 0) {
termIDs.add(term_id);
}
rs2.close();
}
}
rs.close();
} catch (SQLException e) {
System.out.println(e.getMessage() + "in getWholeDocumentTermIDs");
}
return termIDs;
}
The function getWholeDocumentTermIDs(String wikiID) is called 30 k times, meaning for 30 k wikiIDS, so when executing this, steadily more and more RAM is used by my IDE, starting at roughly 1,3 GB to later up to 10 or 11 GB, at which point the process starts to slown heavily. My question is if and how I can reduce/clean up the RAM to fetch all the required data stored in those tables.
Have sqlite table named good_in with columns in_id, good_code, in_group, in_quantity, in_VATPaid
Here is my table example
and have method to insert records into it
public static void inputGoods(GoodsInput goodsinput){
String goodCode = goodsinput.getInGood().getGood_code();
int goodBatch = goodsinput.getInGroup();
int goodQuantity = goodsinput.getInQuantity();
double goodVATPaid = goodsinput.getInVatPaid();
String sqlInsert = "INSERT INTO good_in (good_code, in_group, in_quantity, in_VATPaid)"
+ " VALUES ('" + goodCode + "', " + "'" + goodBatch + "', " + "'" + goodQuantity
+ "', " + "'" +goodVATPaid + "');";
System.out.print(sqlInsert);
Connection conn = ConnectionFactory.ConnectDB();
try{
Statement statement = conn.createStatement();
statement.executeUpdate(sqlInsert);
}
catch(SQLException e){
}
}
Connection class
public static Connection ConnectDB(){
try{
Class.forName("org.sqlite.JDBC");
Connection con = DriverManager.getConnection("jdbc:sqlite:kahuyq.db");
return con;
} catch (HeadlessException | ClassNotFoundException | SQLException ex){ JOptionPane.showMessageDialog(null, ex); }
return null;
}
When I copy the printed query to sqlite manager it adds the row, but from java it ends program with no error but does not add row to my table.
What is wrong?
Have also other method that checks weather the good_code exists in table good which have only 2 columns id and good_code and if does not exist adds it. this method is accessed from GoodsInput constructor. When I delete the method from constructor the other method works fine.
Here is that method
public static void insertGoods(Good g){
String sqlSelect = "Select * from good where good_code = '"
+ g.getGood_code() + "'" ;
String sqlInsert = "INSERT INTO good (good_code)"
+ "VALUES ('" + g.getGood_code() +"')";
Connection conn = ConnectionFactory.ConnectDB();
try{
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(sqlSelect);
while(!rs.next()){
statement.executeUpdate(sqlInsert);
break;
}
}
catch(SQLException e){
}
}
Try to add
conn.commit();
after the execution of your statement.
I have the following function and I am trying to compare the number of students enrolled in a class with the class max. If the number enrolled is greater than the class max, I want to return a message that says, "The Class if Full".
public static void classFullCheck() {
try {
String currentNumberInClassAsString = ("SELECT class_id, COUNT(*) FROM ClassSelector.student_x_class WHERE class_id = " + selectedClass);
rs = myStmt.executeQuery(currentNumberInClassAsString);
int currentNumberInClassAsInt = 0;
if(rs.next()){
currentNumberInClassAsInt = rs.getInt(1);
}
String classSizeAsString = ("SELECT class_size FROM ClassSelector.classes WHERE class_id = " + selectedClass);
rs = myStmt.executeQuery(classSizeAsString);
int classSizeAsInt = 0;
if(rs.next()){
classSizeAsInt = rs.getInt("class_size");
}
if (currentNumberInClassAsInt > classSizeAsInt){
System.out.println("Sorry, this class is Full!");
}
} catch (java.sql.SQLException SQL) {
SQL.printStackTrace();
}
}
I am inserting the classFullcheck() function into the addClass() function like this:
public static void addClass() {
try {
rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes");
while (rs.next()) {
String availableClasses = rs.getString("class_id") + "\t" + rs.getString("class_name") + "\t" + rs.getString("description");
System.out.println(availableClasses);
}
System.out.println("Enter Class ID from Classes Listed Above to Join: ");
selectedClass = sc.nextLine();
rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes WHERE class_id = " + selectedClass);
while (rs.next()) {
classFullCheck();
String innerJoin = (userEnterIdAsName + " has been added to " + rs.getString("class_name") + " " + rs.getString("class_id"));
System.out.println(innerJoin);
String student_x_classJoin = "INSERT INTO student_x_class" + "(student_id, student_name, class_id, class_name)" + "VALUES (?, ?, ?, ?)";
PreparedStatement pStmt = con.prepareStatement(student_x_classJoin);
pStmt.setString(1, user_entered_student_id);
pStmt.setString(2, userEnterIdAsName);
pStmt.setString(3, rs.getString("class_id"));
pStmt.setString(4, rs.getString("class_name"));
pStmt.executeUpdate();
System.out.println("Would you like to enroll " + userEnterIdAsName + " into another class? (Y/N)");
String addAdditionalClass = sc.nextLine();
if (addAdditionalClass.equalsIgnoreCase("Y")) {
addClass();
} else if (addAdditionalClass.equalsIgnoreCase("N")) {
return;
}
}
}
catch (java.sql.SQLException SQL) {
System.out.println("Wait, This Student is already enrolled in this class!");
}
}
I am currently just getting both messages printed out, even if a class is not full. Any suggestions would help a lot.
if (currentNumberInClassAsInt >= classSizeAsInt) {
String updateStatus = "Update ClassSelector.classes SET status = ? WHERE class_id = " + selectedClass;
PreparedStatement pStmt = con.prepareStatement(updateStatus);
pStmt.setString(1, "Closed");
pStmt.executeUpdate();
System.out.println("Sorry, this class is Full! Select a different Class:");
System.out.println("\nSign Up For a Class\n");
addClass();
}
I think you want this:
currentNumberInClassAsInt = rs.getInt(2);
instead of:
currentNumberInClassAsInt = rs.getInt(**1**);
I don't think the ResultSet is 0 based...
Also is rs a global variable because it looks like you are changing your ResultSet rs when you call classFullCheck(). You may not have what you think you do in the ResultSet...
rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes WHERE class_id = " + selectedClass);
while (rs.next()) {
classFullCheck();//****************result set changed here******************
String innerJoin = (userEnterIdAsName + " has been added to " + rs.getString("class_name") + " " + rs.getString("class_id"));
You may think you have this: rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes WHERE class_id = " + selectedClass); in your result set but you change rs in classFullCheck(). You may want to store the data in a different object that way when you run another query you can still access the data.
i have a table - emp_details in mysql
i want to seatch an employ's id number in java.
if it is in the table , then show all the details of employee.
otherwise display an error message.
how i do this
Using JDBC
Here is an example You can build your solution from it.
Statement stmt = null;
String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from " + dbName + ".COFFEES";
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");
System.out.println(coffeeName + "\t" + supplierID + "\t" + price + "\t" + sales + "\t" + total);
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
stmt.close();
}
ResultSet rs1=stmt.executeQuery("SELECT * FROM employee_details where Employee_ID='"+strEmpId+"'");
if(rs1.next()) {
System.out.println("Emp ID : " + rs1.getString(1));
System.out.println("Emp Name : " + rs1.getString(2));
System.out.println("Emp Salary : " + rs1.getString(3));
} else {
System.out.println("Emp ID not found");
}
If you want to know more about SQL just go through HERE