how to get mysql tables in JComboBox - java

i am useing the following code to get only list of mysql tables and add them to the JComboBox. but what I get is only "[]" in the JComboBox! please help me with it
ArrayList<String> tables = new ArrayList<String>();
public ArrayList<String> tablesArray() throws SQLException
{
ResultSet result = connecting.getMetaData().getCatalogs();
while(result.next())
{
tables.add(result.getString(0));
}
return tables;
}
public JComboBox comboBox()
{
JComboBox<ArrayList> combo = new JComboBox<ArrayList>();
combo.addItem(tables);
combo.setBounds(130,30,190,30);
return combo;
}

ArrayList tables = new ArrayList();
is array that contains one or more Items
combo.addItem(tables);
later you added a.m. array as Item, then output could be correct
pass array as constructor, more see in JComboBox API Constructor Summary
better to create an DefaultComboBoxModel (see a.m. API) and add those Items from ResultSet to model directly

Try the following
while(result.next())
{
tables.add(result.getString(1));
}
See this question for more information: How to check if a particular database in mysql already exists using java or this one how to get list of Databases "Schema" names of MySql using java JDBC
However I am a bit confused are you looking for database names? Or are you trying to find table names?
When using MySQL you can always query the information_Schema views for LOADS of information regarding the tables, databases columns etc.

The getCatalogs() method returns catalog names, not table names. I'm not sure what it will do on MySQL, since AFAIK MySQL does not have catalogs.
If you call DatabaseMetaData.getTables(...) and use null for the first param, catalog, it should give you all table names without narrowing the result to any catalog.

you should try this
ResultSetMetaData meta = (ResultSetMetaData) rs.getMetaData();
int columns = meta.getColumnCount();
while(rs.next()){
for(int i =1; i<=columns; i++){
String yourValues = rs.getString(i);
theCombo.addItem(yourValues);
//rs is the result set for the executed query.
}

Here is a complete code to retrieve all tables of a database into JComboBox:
public JComboBox<String> comboBox() throws SQLException
{
ResultSet rs = connecting.getMetaData().getTables(null, null, "%", null);
ResultSetMetaData meta = (ResultSetMetaData) rs.getMetaData();
int columns = meta.getColumnCount();
while(rs.next())
{
String table_names = rs.getString("TABLE_NAME");
combo.addItem(table_names);
}
combo.setBounds(130,30,190,30);
combo.setSelectedIndex(0);
combo.setMaximumRowCount(5);
return combo;
}

Related

How do I get the variables in a column from java and sql?

So say a column is named Names I want to get a ArrayList of every variable inside of this column. Example:
Names
Test
Test1
Test3
River
World
Etc
I want to get all of that into an array list. Thanks for the help!
You're not giving much information in your question (e.g. what is the table you'd like to query), so here's a somewhat generic solution:
public List<String> retrieveAllColumnValues(Connection connection) throws SQLException {
String query = "SELECT Names FROM MyTable";
List<String> values = new ArrayList<>();
try (Statement stmt = connection.createStatement()) {
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
values.add(rs.getString("Names"));
}
rs.close();
}
return values;
}
Getting data from the database through JDBC roughly consist of the following parts:
You have a Connection which you use for creating SQL Statements
When you execute the Statement, you get a ResultSet, which contains the values returned by your query
You iterate through the ResultSet and do what you need to with the values

add column to jtable dynamically on netbeans

my code is this :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model=(DefaultTableModel)pl.getModel();
String urlBaseDonnes="jdbc:mysql://localhost:3306/test";
Connection con;
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException ex){
System.out.println(ex);
}
try{
con =DriverManager.getConnection(urlBaseDonnes,"root","");
try (Statement stmt = con.createStatement()) {
ResultSet rs = stmt.executeQuery("SELECT * FROM news");
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
System.out.println("resultSet MetaData column Count=" + numberOfColumns);
int j=0;
pl.setModel(new javax.swing.table.DefaultTableModel(new Object [][] {},new String [] {"ddd","fgg","nl"}));
// get the name of the column, and changing it
for (int i = 1 ; i <= numberOfColumns; i++) {
ChangeName(pl,j,rsMetaData.getColumnName(i));
System.out.println(rsMetaData.getColumnName(i));
System.out.println(j);
j= j+1;
}
String query="SELECT * FROM news";
rs=stmt.executeQuery(query);
//Show the database
while(rs.next()){
String id=rs.getString("id");
String titre=rs.getString("titre");
String contenu=rs.getString("contenu");
model.addRow(new Object[]{id,titre,contenu});
}
rs.close();
}
con.close();
System.out.println("close the database");
}catch(SQLException ex){
System.out.println(ex);
}
}
My goal is to change the name of the columns dynamically when i change the name of my table, this code can change the name of the column but when it's come to showing the content of the database it doesn't work, also i can't add column, for exemple if i choose a table that have 4 column, i'll have an error. I tried to add column using a DefaultTableModel but it didn't work.
could you please help me with the part of adding column dynamically ? and tell me why this code doesn't show what's on the database ?
Thanks
that the data that are in my database are not shown. this code only changes the name of the column.
First you access the TableModel of the table:
DefaultTableModel model=(DefaultTableModel)pl.getModel();
Then you change the TableModel of the table:
pl.setModel(new javax.swing.table.DefaultTableModel(new Object [][] {},new String [] {"ddd","fgg","nl"}));
Then you add the data from the database to the "old" model:
model.addRow(new Object[]{id,titre,contenu});
So the data is NOT added to the current model.
If you want to create a new model then your code should be something like:
DefaultTableModel model = DefaultTableModel(Object[] columnNames, int rowCount);
pl.setModel( model );
Then your code will add the database data to the real model.
The question is why are you trying to hardcode the column name? When you do a select * from the database you don't know how many columns of data will be returned. You should be using more generic code. See the TableFromDatabaseExample.java code from Table From Database.

How to change from jList to JTable (data from DB have many columns and rows)

I'll try to explain as good as I possibly can. I'm a noob and have been trying to fix this for hours now...
I have made a Java application that shows data from a Database that it is connected to. (ODBC/Microsoft SQL).
When I made the GUI for the application I decided to show the data in a jList.
I then realized that the information is too much and that I need column names etc (therefore an jTable)
What I want to do is to CHANGE so that the data shows up in a jTable instead of the jList. But I have no clue how to do it.
This is what the code looks like for now:
GUI
private void jComboBox1_actionPerformed(ActionEvent e)throws SQLException {
String selected = jComboBox1.getSelectedItem().toString();
String[]tmp = conn.showTable1(selected);
jList1.setListData(tmp);
}
Controller
public String[] showTable1(String table)throws SQLException {
ArrayList<String> list1 = dal.showTable1(table);
return list1.toArray(new String[list1.size()]);
}
Data Access Layer
public ArrayList<String> showTable1(String table)throws SQLException {
ArrayList<String> list1 = new ArrayList<String>();
Statement stmt = con.createStatement();
String query1 = "select * from [" +table+"]";
System.out.println(query1);
ResultSet rset = stmt.executeQuery(query1);
ResultSetMetaData rsmd = rset.getMetaData();
while (rset.next()) {
String result = "";
for(int i = 1; i < rsmd.getColumnCount(); i++) {
result += rset.getString(i) + "\t" + "\t";
//
}
list1.add(result);
}
return list1;
}
Please help!
Kind Regards, Chris
See Table From Database for a couple of simple suggestions:
Search the web for an existing ResultSetTableModel.
Use the TableFromDatabase Example code
Use the ListTableModel presented in the blog

What method to create, in order to delete the rows of information from the database?

This is my first time making an application and I am quite new with connecting the netbeans IDE to the MySQL database. I have a delete button in a Jpanel, and I want to be able to delete added rows. At the moment I can delete the added rows but they are of course not delete within the SQL DB which means they will remain there when I restart the application.
This is what I have to delete the rows so far
private void removeProductBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
DefaultTableModel model = (DefaultTableModel) this.productTable.getModel();
int[] rows = productTable.getSelectedRows();
for(int i=0;i<rows.length;i++){
model.removeRow(rows[i]-i);
// If I highlight the rows and delte the, they are still in the SQL database.
//How to remove the complete data from the row in the SQL database? What method to write?
String sql = "DELETE FROM Product WHERE ProductID = ?";
Below I have my query to put it inside the database. (so you know what variables I am using)
public ResultSet insertQuery(String query) {
ResultSet result = null;
try {
Statement statement = connection.createStatement();
statement.executeUpdate(query);
result = statement.getGeneratedKeys();
} catch (SQLException e) {
System.err.println(e);
}
return result;
You have a '?' in your sql but you aren't using prepared statement.
For example's sake try:
String sql = "DELETE FROM Product WHERE ProductID = " + rows[i]-i
Question marks are used for prepared statements in java which (among other things) is used for sanitising inputs. Once you get the rest of your code working you should investigate it.

MySQL Java JDBC: How to get the name of an auto-incremented column?

I'm working on a program that makes using MySQL databases simpler. Right now I have to create forms to add and edit data from the tables within the database. The problem is that when I create the form I don't want to display fields for auto-incremented columns. All I need is the name of the column to fix this but I have no idea how to find the name of a auto-incremented column. I have tried looking up the answer but all I find is information about finding auto - generated keys. Can someone help me or point me in the right direction? Thanks for the help.
UPDATE:
Thanks for the help. Base on the answers below I came up with this method:
public Vector<String> getAutoIncrementedColumns(String table) {
Vector<String> columnNames = new Vector<String>();
Connection connection;
try {
connection = DriverManager.getConnection(getUrl(), getUser(),
getPassword());
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("Select * from "+table);
int columnCount = result.getMetaData().getColumnCount();
for(int i = 1; i <=columnCount; i++){
if(result.getMetaData().isAutoIncrement(i)){
columnNames.add(result.getMetaData().getColumnName(i));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return columnNames;
}
Once you have a ResultSet, you can call its getMetaData method to the get a ResultSetMetaData object. From there, you can use the isAutoIncrement method to determine if a column is an AUTO_INCREMENT column, and getColumnName to get the column's name.
The EXTRA column of the INFORMATION_SCHEMA.COLUMNS table should have this information.
PS:this is from top of my head. Don't have MySql handy, you may have to test to confirm.
The class ResultSetMetaData can provide this information.
But you would have to execute a select * first to get a result set. You could do
SELECT * FROM table LIMIT 1
to get the result set.
If you have access to the schema information_schema these informations are available from the tables
TABLES (column: auto_increment, 0 = no, 1 = yes)
COLUMNS (column: extra = auto_increment for the specific column)

Categories

Resources