Is Passing a result set in java possible? - java

I'm trying to make a command where i can send different queries to a SQLite / Mysql DB and return the resultset to whatever function is calling. It needs to be able to process whether there is 2 columns or 15.
The below doesn't work - presumably because it closes the resultset / connection but I'm not sure how else to do it.
Thoughts?
public static ResultSet queryDB(String query) {
try {
Connection connection = DriverManager.getConnection("jdbc:sqlite:" + Settings.SQLITE_DB_PATH);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
resultSet.close();
statement.close();
connection.close();
return resultSet;
} catch (SQLException ex) {
Logger.getLogger(SQLInterp.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}

You basically have 3 choices:
Don't close the ResultSet, Statement, and Connection in the method, handing off responsibility for doing that back to the caller.
Not recommended, since it is error-prone, and breaks well-formed code structure paradigms.
Pass in an object with the logic that is needed for processing the data, as suggested by Jacob G..
E.g. use a Java 8+ Consumer:
public static void queryDB(String query, Consumer<ResultSet> processor) {
try (
Connection connection = DriverManager.getConnection("jdbc:sqlite:" + Settings.SQLITE_DB_PATH);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
) {
processor.accept(resultSet);
} catch (SQLException ex) {
Logger.getLogger(SQLInterp.class.getName()).log(Level.SEVERE, null, ex);
}
}
Then call it like this:
SQLInterp.queryDB("SELECT * FROM foo", rs -> {
while (rs.next()) {
// process data here
}
});
Read all the data into memory in a generic data structure, e.g. List<Map<String, Object>>:
This of course assumes that query has good unique names for each column.
public static List<Map<String, Object>> queryDB2(String query) {
try (
Connection connection = DriverManager.getConnection("jdbc:sqlite:" + Settings.SQLITE_DB_PATH);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
) {
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
String[] name = new String[columnCount];
for (int i = 0; i < columnCount; i++)
name[i] = metaData.getColumnLabel(i + 1);
List<Map<String, Object>> rows = new ArrayList<>();
while (resultSet.next()) {
Map<String, Object> row = new LinkedHashMap<>();
for (int i = 0; i < columnCount; i++)
row.put(name[i], resultSet.getObject(i + 1));
rows.add(row);
}
return rows;
} catch (SQLException ex) {
Logger.getLogger(SQLInterp.class.getName()).log(Level.SEVERE, null, ex);
}
}

Related

how to sort a table from database

I want to be able to sort a table from the database, according to either the quatity or the name, but how do i decided what happens in what case?
Below is the code for the table.
public void tableupdate(JTable jTable1, String fill) {
try {
try {
Class.forName("org.h2.Driver");
Connection con = DriverManager.getConnection("jdbc:h2:file:D:/Inventory.db", "sa", "");
Statement stat = con.createStatement();
fill = "SELECT * FROM BOOKDESC ";
ResultSet rs = stat.executeQuery(fill);
while (jTable1.getRowCount() > 0) {
((DefaultTableModel) jTable1.getModel()).removeRow(0);
}
int columns = rs.getMetaData().getColumnCount();
while (rs.next()) {
Object[] row = new Object[columns];
for (int i = 1; i <= columns; i++) {
row[i - 1] = rs.getObject(i);
}
((DefaultTableModel) jTable1.getModel()).insertRow(rs.getRow() - 1, row);
}
rs.close();
stat.close();
con.close();
} catch (ClassNotFoundException e) {
JOptionPane.showMessageDialog(null, e);
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e);
}
}
MySQL is offering a method for sorting data in your SELECT statement, it's called ORDER BY.
Usage is found here.
This way, your code doesn't have to do the work, as your ResultSet already gets sorted data.

importing last row of mysql database in all rows of jtable (Java Swing)

I'm trying to import all of the data from mysql database into a jtable using arraylists but something isn't working right, as i get the number of rows right but they're all values of the last row
Here's the code
public ArrayList<medicaments> medicaments_list() {
ArrayList<medicaments> medicament_lists = new ArrayList<medicaments>();
String select_nom_type_med = "select * from medicaments where login=?";
PreparedStatement stmt;
ResultSet rs2;
medicaments med;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
stmt = con.prepareStatement(select_nom_type_med);
stmt.setString(1, Utilisateur.getLogin());
rs2 = stmt.executeQuery();
while (rs2.next()) {
emptytable = false;
med = new medicaments(rs2.getInt("med_id"), rs2.getString("login"), rs2.getString("med_nom"), rs2.getString("med_type"), rs2.getString("date_debut"), rs2.getString("date_fin"), rs2.getString("frequence"), rs2.getString("temps_1"), rs2.getString("temps_2"), rs2.getString("temps_3"), rs2.getString("temps_4"), rs2.getString("temps_5"), rs2.getString("Stock"), rs2.getString("rappel_stock"));
medicament_lists.add(med);
}
} catch (ClassNotFoundException e1) {
System.out.println(e1);
} catch (SQLException e1) {
System.out.println(e1);
}
return medicament_lists;
}
public void populate_jTable_from_db() {
ArrayList<medicaments> dataarray = medicaments_list();
model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(dataarray.size());
int row = 0;
for (medicaments data : dataarray) {
model.setValueAt(data.get_nom_med(), row, 0);
model.setValueAt(data.get_type_med(), row, 1);
row++;
}
jTable1.setModel(model);
}
and here's the result :(there's 3 rows in my database and po is the last one i added)
Make sure your recordset actually contains something and it's what you really want:
while (rs2.next()) {
if (rs2.getString("login").equals(Utilisateur.getLogin())) {
emptytable = false;
med = new medicaments(rs2.getInt("med_id"), rs2.getString("login"),
rs2.getString("med_nom"), rs2.getString("med_type"),
rs2.getString("date_debut"), rs2.getString("date_fin"),
rs2.getString("frequence"), rs2.getString("temps_1"),
rs2.getString("temps_2"), rs2.getString("temps_3"),
rs2.getString("temps_4"), rs2.getString("temps_5"),
rs2.getString("Stock"), rs2.getString("rappel_stock"));
medicament_lists.add(med);
}
}

Java - NULL ResultSet

I have a function to fetch data from MySQL table
public ResultSet getAddressID(String city) throws SQLException{
String q = "SELECT PK_ADDRESS_ID FROM tbl_addresses WHERE city =" + "\""+ city+ "\";";
ResultSet rs = executeSearch(q);
return rs;
}
When I try System.out.println(n.getAddressID("Sheffield")); it returns null. Why this happened even though there are data in my table (see picture).
public ResultSet executeSearch(String q){
openConnection();
try{
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(q);
closeConnection();
return resultSet;
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
finally {
closeConnection();
return null;
}
}
The problem appears to be in your executeSearch method; the finally block will always execute, so by returning null in the finally block, you essentially override what you returned in the try block!
This could be an alternative solution; note that I'm returning at the end of the method instead of within any parts of the try-catch-finally block.
/**
* Converts a provided ResultSet into a generic List so that the
* ResultSet can be closed while the data persists.
* Source: http://stackoverflow.com/a/7507225/899126
*/
public List convertResultSetToList(ResultSet rs) throws SQLException
{
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
List list = new ArrayList(50);
while (rs.next())
{
HashMap row = new HashMap(columns);
for(int i = 1; i <= columns; ++i)
{
row.put(md.getColumnName(i), rs.getObject(i));
}
list.add(row);
}
return list;
}
public List executeSearch(String q)
{
List toReturn;
openConnection();
try {
Statement statement = connection.createStatement();
toReturn = this.convertResultSetToList(statement.executeQuery(q));
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
toReturn = new ArrayList();
}
finally {
closeConnection();
}
return toReturn;
}

executeQuery is always empty

I'm trying to get the data from database but get nothing. The problem is
ResultSet resultSet = statement.executeQuery(readQuery);
always empty. And
while (resultSet.next())
is never executing.
Would really appreciate any help
public class DB {
public Connection connect() {
Connection connection = null;
try {
String databaseURL = "jdbc:derby://localhost:1527/DB;create=true;user=user;password=password";
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
connection = DriverManager.getConnection(databaseURL);
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {
Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
}
return connection;
}
ArrayList read(Connection connection, String table, String column, String value) {
ArrayList results = new ArrayList();
Statement statement = null;
try {
statement = connection.createStatement();
String readQuery = "select * from " + table + " where " + column + " = '" + value + "'";
out.print(readQuery);
ResultSet resultSet = statement.executeQuery(readQuery);
while (resultSet.next()) {
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
int numberOfColumns = resultSetMetaData.getColumnCount();
out.print("Read\n");
for (int i = 1; i < numberOfColumns + 1; i++) {
results.add(resultSet.getString(i));
}
}
statement.close();
connection.close();
}
catch (SQLException ex) {
}
return results;
}
}

Getting empty resultSet for simple query

gurus,
I am new to Java SQL, and need some help.
I'm trying to get a parameter from MS SQL Server 2008. The data is definitely there - it is a current and valid DB, and I'm trying to use the users records to get cridentials for another application.
I asserted the following query:
String query = "SELECT [USER].qc_number FROM [USER] WHERE "[USER].login_name = '"
+ userNameInput + "' AND [USER].password = '" + passWordInput + "';";
Where userNameInput and passWordInput are received from the user. The URL, query and driver class are definitely correct: I checked the DB schema both from the application and from the server views. Furthermore, I verified all the Exceptions systems by changing parameters one by one, resulting in correct Exceptions messages. However, I get a resultSet with 1 column and 0 rows.
The code is below:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class trOdbc
{// database URL
final String DB_URL = "***";
final String Class_URL = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private Connection connection = null; // manages connection
private Statement statement = null; // query statement
private ResultSet resultSet = null; // manages results
private Boolean connectedToDatabase = false;
// ----------------------------------------------------------
public void createJdbcConnection()
{ // connect to database books and query database
if (connectedToDatabase)
{ return; }
try
{ // connectedToDatabase is false - establish the connection
Class.forName(Class_URL);
connection = DriverManager.getConnection
(DB_URL, "***", "***" );
statement = connection.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
connectedToDatabase = true;
}
catch (SQLException ex)
{ System.out.println ("SQL Exception in connection establishment: " + ex); }
catch (ClassNotFoundException ex)
{ System.out.println ("Class not found exception in query process: " + ex); }
}
// ----------------------------------------------------------
public String [][] processJdbcQuery (String query)
{
createJdbcConnection ();
if (!connectedToDatabase)
{ return null; }// the connection wasn't established
try
{// query database
resultSet = statement.executeQuery(query);
int columns = resultSet.getMetaData().getColumnCount();
int rows = 0;
if (resultSet != null)
{
resultSet.beforeFirst();
resultSet.last();
rows = resultSet.getRow();
}
String [][] tempData = new String[rows][columns];
resultSet.beforeFirst();
rows = 0;
while (resultSet.next())
{
for (int x = 1; x <= columns; x++)
{
tempData [rows][x - 1] = resultSet.getString (x);
}
rows++;
}
CloseJdbcConnection ();
return tempData;
}
catch (SQLException ex)
{
System.out.println ("SQL Exception in query process: " + ex);
CloseJdbcConnection ();
return null;
}
} // end processJdbcQuery
// ----------------------------------------------------------
public void CloseJdbcConnection()
{
if ( connectedToDatabase )
{// close Statement and Connection. resultSet is closed automatically.
try
{
statement.close();
connection.close();
connectedToDatabase = false;
}
catch (SQLException ex)
{ System.out.println ("SQL Exception in connection closure: " + ex); }
} // end if
} // end method CloseJdbcConnection
} // end class trOdbc
Why don't you use Prepared Statement instead ?
Here is a good tutorial for using prepared statement in java
In your case it would be :
String query = "SELECT [USER].qc_number FROM [USER] " +
"WHERE [USER].login_name = ? AND [USER].password = ?;";
And then set it with different values each time you execute it like :
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, userNameInput);
ps.setString(2, passWordInput);
resultSet = ps.executeQuery();

Categories