Results 1 to 2 of 2
  1. #1
    dub
    dub is offline Member
    Join Date
    Jan 2014
    Posts
    2
    Rep Power
    0

    Default Gui + jdbc connection to mysql.

    Hello,

    im learning java se and im kinda noob on java and sorry about my english. :)
    Ok, i did want/try to do Gui what connect mysql database and printing out all tables,rows and columns. I want to do JTreeTabel for that.
    But right now i just trying to print all tables and columns in JTable.
    I did create jdbc class whit jdbc connection to mysql database, i did got data from database and System.out.print data to console.. But i got the problem when i did try to get this data to JTable.

    ...
    TableModel dataModel = new AbstractTableModel() {
    JDBC jdbc = new JDBC();
    Object[][] data = {{jdbc.getTableName()}}; <---this is silly^^ but i wanna get tableName and columnName from JDBC class

    @Override
    public int getColumnCount() {
    return data[0].length;
    }

    ....etc


    __________________________________________________ __________________________________________________ ________________
    package sqltest;

    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;

    public class SQLTest {
    public static void main(String[] args) {

    try {
    UIManager.setLookAndFeel(
    UIManager.getCrossPlatformLookAndFeelClassName());
    }
    catch (UnsupportedLookAndFeelException e) {
    // handle exception
    }
    catch (ClassNotFoundException e) {
    // handle exception
    }
    catch (InstantiationException e) {
    // handle exception
    }
    catch (IllegalAccessException e) {
    // handle exception
    }
    Gui g = new Gui();//Create and show the GUI.
    g.label();

    }
    }
    __________________________________________________ __________________________________________________ ________________
    package sqltest;
    import java.sql.*;

    public class JDBC{
    private String host;
    private String port;
    private String database;
    private String username;
    private String password;
    Connection connect = null;
    private String TableName;
    private String ColumnName;
    String list;

    protected void connection() throws SQLException{

    try {

    Class.forName("com.mysql.jdbc.Driver").newInstance ();

    connect = DriverManager.getConnection("jdbc:mysql://"+host+"/"+database,username,password);
    if(connect != null){
    System.out.println("Connection succeed!!");
    }
    DatabaseMetaData mTable = connect.getMetaData();
    ResultSet table = mTable.getTables(null, null, "%",null);
    while (table.next()) {
    TableName = table.getString(3);
    System.out.println("Table name is : "+ TableName+"\n");// all table names are in TableName variable

    DatabaseMetaData mColum = connect.getMetaData();
    ResultSet columns = mColum.getColumns(null, null, TableName, "%");
    while (columns.next()) {
    ColumnName = columns.getString(4);
    System.out.println("\t"+ColumnName);// all table columns names are in ColumnName variable
    }
    }
    }catch(ClassNotFoundException ex) {
    System.out.println("Error: unable to load driver class!"+ ex);
    System.exit(1);
    }catch(IllegalAccessException ex) {
    System.out.println("Error: access problem while loading!"+ ex);
    System.exit(2);
    }catch(InstantiationException ex) {
    System.out.println("Error: unable to instantiate driver!"+ ex);
    System.exit(3);
    }
    }
    public String getHost() {
    return this.host;
    }

    public void setHost(String host) {
    this.host = host;
    }

    public String getPort() {
    return this.port;
    }

    public void setPort(String port) {
    this.port = port;
    }

    public String getDatabase() {
    return this.database;
    }

    public void setDatabase(String database) {
    this.database = database;
    }

    public String getUsername() {
    return this.username;
    }

    public void setUsername(String username) {
    this.username = username;
    }

    public String getPassword() {
    return this.password;
    }

    public void setPassword(String password) {
    this.password = password;
    }

    public String getTableName() {
    return TableName;
    }

    public void setTableName(String TableName) {
    this.TableName = TableName;
    }

    public String getColumnName() {
    return ColumnName;
    }

    public void setColumnName(String ColumnName) {
    this.ColumnName = ColumnName;
    }

    }
    __________________________________________________ __________________________________________________ ________________
    package sqltest;
    import java.awt.event.*;
    import javax.swing.*;

    public class Gui extends JFrame{

    JFrame jf = new JFrame();
    JLabel la = new JLabel();
    JButton btn = new JButton("Connect");
    JButton btn2 = new JButton("Disconnect");
    JPanel test = new JPanel();
    JTable table = new JTable();

    public void label(){

    try{
    tableData td = new tableData();
    jf.setVisible(true);
    jf.setSize(800,600);
    jf.setTitle("Test");
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.setLocationRelativeTo(null);
    jf.add(la);
    la.add(btn);
    la.add(btn2);
    la.add(td.scrollpane);
    td.scrollpane.setBounds(20, 120, 750, 400);
    btn.setBounds(500, 30, 100, 30);


    btn.addMouseListener(new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent e) {
    JDBC jdbc = new JDBC();
    if(jdbc.connect != null){
    int dialogButton = JOptionPane.YES_NO_OPTION;
    JOptionPane.showConfirmDialog (null, "Are you sure you wanat to connect to other server ?","WARNING", dialogButton);
    if(dialogButton == JOptionPane.YES_OPTION) {
    Connect l = new Connect();
    l.popUp();
    if(dialogButton == JOptionPane.NO_OPTION) {
    remove(dialogButton);
    }
    }
    }else if(jdbc.connect == null){
    Connect l = new Connect();
    l.popUp();
    }
    }
    });
    btn2.setBounds(650, 30, 100, 30);
    }catch(Exception e){
    e.printStackTrace();
    }
    }
    }
    __________________________________________________ __________________________________________________ ________________
    package sqltest;

    import java.awt.event.*;
    import java.sql.*;
    import java.util.logging.*;
    import javax.swing.*;

    public class Connect extends Gui {
    JFrame frame = new JFrame();
    JLabel label = new JLabel();
    JButton submit = new JButton("Connect");
    JTextField host = new JTextField("host");
    JTextField port = new JTextField("");
    JTextField database = new JTextField("database");
    JTextField username = new JTextField("username");
    JTextField password = new JTextField("password");

    public void popUp(){
    frame.setVisible(true);
    frame.setSize(400,300);
    frame.setTitle("Connect");
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_C LOSE);
    frame.add(label);
    label.add(host);
    label.add(port);
    label.add(database);
    label.add(username);
    label.add(password);
    label.add(submit);
    host.setBounds(60, 10,150, 30);
    port.setBounds(220, 10, 50, 30);
    database.setBounds(60,50, 100, 30);
    username.setBounds(60,100, 100, 30);
    password.setBounds(60,150, 100, 30);
    submit.setBounds(250, 200, 100, 30);

    submit.addMouseListener(new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent e ) {
    JDBC jdbc = new JDBC();
    jdbc.setHost(host.getText());
    jdbc.setDatabase(database.getText());
    jdbc.setUsername(username.getText());
    jdbc.setPassword(password.getText());
    try {
    jdbc.connection();
    if( jdbc.connect != null){
    frame.setVisible(false);
    }

    } catch (SQLException ex) {
    Logger.getLogger(Connect.class.getName()).log(Leve l.SEVERE, null, ex);
    System.out.println("Logger error");
    }
    }
    });
    }
    }
    __________________________________________________ __________________________________________________ ________________
    package sqltest;
    import javax.swing.*;
    import javax.swing.table.*;

    public class tableData extends JFrame{

    TableModel dataModel = new AbstractTableModel() {
    JDBC jdbc = new JDBC();
    Object[][] data = {{jdbc.getTableName()}};

    @Override
    public int getColumnCount() {
    return data[0].length;
    }

    @Override
    public int getRowCount() {
    return data.length;
    }

    @Override
    public Object getValueAt(int row, int col) {
    return data[row][col];
    }

    @Override
    public void setValueAt(Object val, int row, int col) {
    data[row][col] = val;
    // Indicate the change has happened:
    fireTableDataChanged();
    }

    @Override
    public boolean isCellEditable(int row, int col) {
    return true;
    }
    };
    JTable table = new JTable(dataModel);
    JScrollPane scrollpane = new JScrollPane(table);

    }

  2. #2
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,236
    Rep Power
    7

    Default Re: Gui + jdbc connection to mysql.

    Here is a simple example that gets the tables from the data base and then when you select the table it will display the columns in the table:

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    
    public class DatabaseInformation extends JFrame implements ActionListener
    {
        DatabaseMetaData dmd;
        ResultSet rs;
        ResultSetMetaData md;
        int columns;
        JComboBox comboBox;
        JTable table;
        String catalog;
    
        public DatabaseInformation()
        {
            comboBox = new JComboBox();
            Vector columnNames = new Vector();
            Vector data = new Vector();
    
            try
            {
                //  Connect to the Database
    
                String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
    //            String url = "jdbc:odbc:Teenergy";  // if using ODBC Data Source name
                String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:/teenergy/data/teenergy.mdb";
                String userid = "";
                String password = "";
    
                Class.forName( driver );
                Connection connection = DriverManager.getConnection( url, userid, password );
                dmd = connection.getMetaData();
    
                //  Get the first Catalog
                //  Note: the result set can contain multiple catalogs, just look at the first one
    
                rs = dmd.getCatalogs();
    
                if (rs.next())
                {
                    catalog = rs.getObject(1).toString();
                    System.out.println( catalog );
                }
    
                rs.close();
    
                //  Get Tables
    
                rs = dmd.getTables(catalog, null, null, new String[] { "TABLE" });
                md = rs.getMetaData();
                columns = md.getColumnCount();
    
                while (rs.next())
                {
                       comboBox.addItem( rs.getObject(3) );
                }
    
                rs.close();
    
            }
            catch(Exception e)
            {
                System.out.println( e );
            }
    
            comboBox.addActionListener( this );
            getContentPane().add(comboBox, BorderLayout.NORTH);
    
            //  Create table with database data
    
            table = new JTable();
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane );
        }
    
        public void actionPerformed(ActionEvent e)
        {
            String table = (String)comboBox.getSelectedItem();
            displayTableColumns( table );
        }
    
        private void displayTableColumns(String tableName)
        {
            try
            {
                //  Get Columns
    
                rs = dmd.getColumns(catalog, null, tableName, null);
                md = rs.getMetaData();
                int columns = md.getColumnCount();
                Vector columnNames = new Vector(columns);
                Vector data = new Vector();
    
                //  Get column names
    
                for (int i = 1; i <= columns; i++)
                {
                    columnNames.addElement( md.getColumnName(i) );
                }
    
                //  Get row data
    
                while (rs.next())
                {
                    Vector row = new Vector(columns);
    
                    for (int i = 1; i <= columns; i++)
                    {
                        row.addElement( rs.getObject(i) );
                    }
    
                    data.addElement( row );
                }
    
                rs.close();
    
                //  Reset Table
    
                DefaultTableModel model = new DefaultTableModel(data, columnNames);
                table.setModel( model );
            }
            catch(Exception e)
            {
                System.out.println( e );
            }
    
        }
    
        public static void main(String[] args)
        {
            DatabaseInformation frame = new DatabaseInformation();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible(true);
        }
    }
    The code is for an Access database so you will need to change the URL for MySQL.

Similar Threads

  1. Replies: 2
    Last Post: 06-22-2013, 05:26 PM
  2. Replies: 5
    Last Post: 09-25-2012, 05:36 PM
  3. JDBC Problem - com.mysql.jdbc.Driver
    By icu222much in forum Advanced Java
    Replies: 5
    Last Post: 11-22-2011, 04:54 PM
  4. Applet connection to MySQL database using JDBC
    By Ryco in forum Java Applets
    Replies: 4
    Last Post: 02-25-2011, 04:33 AM
  5. MySQL/JDBC Mysql query output
    By thelinuxguy in forum Advanced Java
    Replies: 4
    Last Post: 02-13-2009, 01:57 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •