My array doesn't get the content of the database - java

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

Related

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

How to get all data with column name in mysql databases

I create this code for get column name in sql databases. But now I ant to modify above code for get all table data with column name. Then get all data and convert to jsonarray and pass. How I modify this code for get all table data with column name.
#Override
public JSONArray getarray(String sheetName) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
con.setAutoCommit(false);
PreparedStatement pstm = null;
Statement stmt = null;
//-----------------------Drop earliye table -------------------------------------------------------------
try {
String sqldrop = "select COLUMN_NAME from information_schema.COLUMNS where TABLE_NAME='" + sheetName.replaceAll(" ", "_") + "'";
System.out.println(sqldrop);
PreparedStatement mypstmt = con.prepareStatement(sqldrop);
ResultSet resultSet = mypstmt.executeQuery();
JSONArray jsonArray = new JSONArray();
while (resultSet.next()) {
int total_rows = resultSet.getMetaData().getColumnCount();
JSONObject obj = new JSONObject();
for (int i = 0; i < total_rows; i++) {
String columnName = resultSet.getMetaData().getColumnLabel(i + 1).toLowerCase();
Object columnValue = resultSet.getObject(i + 1).toString().replaceAll("_", " ");
// if value in DB is null, then we set it to default value
if (columnValue == null) {
columnValue = "null";
}
/*
Next if block is a hack. In case when in db we have values like price and price1 there's a bug in jdbc -
both this names are getting stored as price in ResulSet. Therefore when we store second column value,
we overwrite original value of price. To avoid that, i simply add 1 to be consistent with DB.
*/
if (obj.has(columnName)) {
columnName += "1";
}
obj.put(columnName, columnValue);
}
jsonArray.put(obj);
}
mypstmt.close();
con.commit();
return jsonArray;
} catch (Exception e) {
System.out.println("There is no exist earlyer databases table!..... :( :( :( **************** " + sheetName.replaceAll(" ", "_"));
}
//----------------------------------------------------------------------------
} catch (ClassNotFoundException e) {
System.out.println(e);
} catch (SQLException ex) {
Logger.getLogger(PassArrayDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("%%%%%%%%%%");
return null;
}
My target is get all data with column name and above data pass html page as a json. So if you have any method for get all data with column name is suitable for me.
// code starts here
// This method retrieves all data from a mysql table...
public void retrieveAllData( String host, String user, String pass, String query) {
JTextArea textArea = new JTextArea();
try(
Connection connection = DriverManager.getConnection( host, user, pass )
Statement statement = connection.createStatement()
ResultSet resultSet = statement.executeQuery(query)) {
ResultSetMetaData metaData = resultSet.getMetaData();
int totalColumns = metaData.getColumnCount();
for( int i = 1; i <= totalColumns; i++ ) {
textArea.append( String.format( "%-8s\t", metaData.getColumnName(i) ) );
}
textArea.append( "\n" );
while( resultSet.next() ) {
for( int i = 1; i <= totalColumns; i++ ) {
Object object = resultSet.getObject(i).toString();
textArea.append( String.format("%-8s\t", object) );
}
textArea.append( "\n" );
}
}
}

how to get multiple values from one text field with delimiter and save each to database

actually I have 10-30 dummies to get the value from txtCC, but i'd only used 3 dummies for example below..
So how do I get each values and save it directly to my database without using dummy? It's a big deal coz' my code was too large to compile using those dummies..
THANKS for any help..
private void bSaveActionPerformed(java.awt.event.ActionEvent evt)
{
// Save to database
String cc = txtCC.getText();
String delimiter = ",";
String[] temp;
temp = cc.split(delimiter);
for(int i = 0; i < temp.length; i++)
if(i==0) {
txtC1.setText(temp[0]);
txtC2.setText("0");
txtC3.setText("0"); }
else if (i==1) {
txtC1.setText(temp[0]);
txtC2.setText(temp[1]);
txtC3.setText("0"); }
else if (i==2) {
txtC1.setText(temp[0]);
txtC2.setText(temp[1]);
txtC3.setText(temp[2]); }
try {
String cc1 = txtC1.getText(); int CC1 = Integer.parseInt(cc1);
String cc2 = txtC2.getText(); int CC2 = Integer.parseInt(cc2);
String cc3 = txtC3.getText(); int CC3 = Integer.parseInt(cc3);
int opt = JOptionPane.showConfirmDialog(null,"Are you sure you want to save this record? ");
if (opt == 0){
if(!txtC1.getText().equals("0")) {
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "Select * from tbl_liqinfo";
rs = stmt.executeQuery(sql);
rs.next();
rs.moveToInsertRow();
rs.updateInt("CC", CC1);
rs.insertRow();
rs.close();
}
if(!txtC2.getText().equals("0")) {
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "Select * from tbl_liqinfo";
rs = stmt.executeQuery(sql);
rs.next();
rs.moveToInsertRow();
rs.updateInt("CC", CC2);
rs.insertRow();
rs.close();
}
if(!txtC3.getText().equals("0")) {
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "Select * from tbl_liqinfo";
rs = stmt.executeQuery(sql);
rs.next();
rs.moveToInsertRow();
rs.updateInt("CC", CC3);
rs.insertRow();
rs.close();
}
}
}
catch (SQLException err){
JOptionPane.showMessageDialog(FrmEmpLiquidation.this, err.getMessage());
}
}
Instead of using dummies, create simple small methods and make use of it. This will reduce you line of code. and also easy to understand.
private void bSaveActionPerformed(java.awt.event.ActionEvent evt){
// Save to database
String cc = txtCC.getText();
String delimiter = ",";
String[] temp;
temp = cc.split(delimiter);
for(int i = 0; i < temp.length; i++)
insertData(temp[i]);
}
public void insertData(final String data){
txtC1.setText(data);
try {
String cc1 = txtC1.getText(); int CC1 = Integer.parseInt(cc1);
int opt = JOptionPane.showConfirmDialog(null,"Are you sure you want to save this record? ");
if (opt == 0){
if(!txtC1.getText().equals("0")) {
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "Select * from tbl_liqinfo";
rs = stmt.executeQuery(sql);
rs.next();
rs.moveToInsertRow();
rs.updateInt("CC", CC1);
rs.insertRow();
rs.close();
}
}
}
catch (SQLException err){
JOptionPane.showMessageDialog(FrmEmpLiquidation.this, err.getMessage());
}
}

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

Categories