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;
}
Related
I want my function to return the result of the Select statement, but in instead it prints SQLServerResultSet:1. How do I do to print/return the data in my function?
My function should execute the SQL statement and store the result in a variable.
public ResultSet selectSubmissions(int department) {
Connection connection = Database.getConnection();
String sql = "SELECT * FROM [MyDB_Widget].[dbo].[surveys] INNER JOIN [MyDB_Widget].[dbo].[instructors] ON surveys.instructor_id = instructors.instructor_id Where instructors.department_id = 2;";
ResultSet rs = null;
try {
Statement statement = connection.createStatement();
rs = statement.executeQuery(sql);
while (rs.next()) {
rs.getString(1); //or rs.getString("column name");
}
} catch (SQLException e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
return rs;
}
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.
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);
}
}
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);
}
}
I want to have an array with the Strings of the result of my Query and the array doesn't add any value. I've already typed my query on my database and it works.
public String[] query() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/repaso?" + "user=root&password=");
Statement sentence = con.createStatement();
ResultSet result = sentence.executeQuery("select marca from marca");
result.last();
int i = result.getRow();
result.beforeFirst();
System.out.println(result);
int x = 0;
String[] array = new String[i];
while (result.next()) {
array[x] = result.getString(1);
x++;
}
result.close();
return array;
} catch (ClassNotFoundException | SQLException e1) {
}
return null;
}