java-mysql program - java

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

Related

How to insert and return an instance of Employee (DAO pattern)

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;
}
}

Up to 11 GB RAM is used by following SQL Statements, how can I optimize RAM usage?

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.

How to print out a specific column from MySQL in java

I am trying to print out all the columns that has the same path as the one that i get from an Image. The main problem is that path='path' is read as a string with the value "path" instead of the value that i have in my path-variable. path = path without the '' is not accepted as a value, and therefore i can't print the columns. if i directly insert path='C:\Users....\' here, it prints out the right columns.
public void getImageInfoFromDatabase(Image image) {
String path = image.getFile().getAbsolutePath();
path = path.replace("\\", "\\\\");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connect = DriverManager.getConnection(url, user, pass);
Statement statement = connect.createStatement();
resultSet = statement.executeQuery("SELECT * FROM image_table WHERE path='path'");
while (resultSet.next()) {
int id = resultSet.getInt(1);
String title = resultSet.getString(2);
String path = resultSet.getString(3);
String tags = resultSet.getString(4);
String latitude = resultSet.getString(5);
String longitude = resultSet.getString(6);
java.util.Date timestamp = resultSet.getTimestamp(7);
System.out.println(id + " " + title + " " + path + " " + tags + " " + latitude + " " + longitude + " " + timestamp);
}
} catch (SQLException | ClassNotFoundException e) {
System.out.println("Error. ");
e.printStackTrace();
}
}
I found out that i had to use the setString method from PreparedStatement to input a value at a specific index. The complete functioning code looks like this:
public boolean getImageInfoFromDatabase(Image image) {
boolean success = true;
String string = image.getFile().getAbsolutePath();
string = string.replace("\\", "\\\\");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connect = DriverManager.getConnection(url, user, pass);
PreparedStatement stmt = connect.prepareStatement("SELECT * FROM image_table WHERE path = ?");
stmt.setString(1, string);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
int id = resultSet.getInt(1);
String title = resultSet.getString(2);
String path = resultSet.getString(3);
String tags = resultSet.getString(4);
String latitude = resultSet.getString(5);
String longitude = resultSet.getString(6);
java.util.Date timestamp = resultSet.getTimestamp(7);
System.out.println(id + " " + title + " " + path + " " + tags + " " + latitude + " " + longitude + " " + timestamp);
success = true;
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
success = false;
}
return success;
}
SELECT * FROM image_table WHERE path='path'

Does SQL cursor use less memory?

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.

java/sql comparing two ints

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.

Categories

Resources