Click here to Skip to main content
15,886,519 members
Articles / Desktop Programming / Swing
Tip/Trick

Java & JDBC & SQLite: Read Data from User-selected db Table and Show in JTable

Rate me:
Please Sign up or sign in to vote.
4.00/5 (2 votes)
4 Sep 2014CPOL 38.6K   951   7   12
A JavaFX/Swing NetBeans 8.0 Project with JFrame created by NetBeans's GUI Builder

Introduction

You can find enough information on the internet about the sterling interaction with databases in .NET (see my article about MS Access, MySQL, SQLite, SQL Server, SQL Server CE), which has convenient built-in tools for this purpose (such as DataSet, etc.). But with Java, this is much worse.

I decided to fill this gap.

Prepare Your Project

Download this jar, add it to your project directory and add a reference to it to your project.

(Tested with its 3.7.2 version)

Import the Necessary Packages

Java
import java.sql.*;
import javax.swing.JOptionPane;
import javax.swing.table.*;

Connect Database

Java
// connect to db (file test.db must lay in the project dir)
// NOTE: it will be created if not exists
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:test.db");

Create Table If It Does Not Exist

Java
?(or run any other SQL query)
// create table "Table 1" if not exists
Statement stmt = conn.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS [Table 1] 
(id INTEGER PRIMARY KEY AUTOINCREMENT, 'text column' TEXT, 'int column' INTEGER);";
stmt.executeUpdate(sql);
stmt.close();

Get All Tables in db into combobox for User Select

Java
// get all tables in db and them names to combobox
ResultSet rs = null;
DatabaseMetaData meta = conn.getMetaData();
rs = meta.getTables(null, null, null, new String[]{"TABLE"});

while (rs.next()) {
    String tableName = rs.getString("TABLE_NAME");
    jComboBox1.addItem(tableName);
}
jComboBox1.updateUI();

Load Selected Table to JTable

Java
private void Select() {
try {
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT * FROM [" + jComboBox1.getSelectedItem() + "];");

    // get columns info
    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();

    // for changing column and row model
    DefaultTableModel tm = (DefaultTableModel) jTable1.getModel();

    // clear existing columns 
    tm.setColumnCount(0);

    // add specified columns to table
    for (int i = 1; i <= columnCount; i++ ) {
        tm.addColumn(rsmd.getColumnName(i));
    }   

    // clear existing rows
    tm.setRowCount(0);

    // add rows to table
    while (rs.next()) {
    String[] a = new String[columnCount];
    for(int i = 0; i < columnCount; i++) {
        a[i] = rs.getString(i+1);
    }
    tm.addRow(a);
}
    tm.fireTableDataChanged();

    rs.close();
    stmt.close();
} catch (Exception ex) { 
    JOptionPane.showMessageDialog(this, ex, ex.getMessage(), WIDTH, null);
}
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
Questionclassnotfoundexception org.sqlite.jdbc after generate jar file Pin
Member 961649325-Sep-14 7:14
Member 961649325-Sep-14 7:14 
Questionexecutable Pin
Member 961649318-Sep-14 17:57
Member 961649318-Sep-14 17:57 
AnswerRe: executable Pin
Emiliarge18-Sep-14 19:49
professionalEmiliarge18-Sep-14 19:49 
GeneralRe: executable Pin
Member 961649319-Sep-14 4:16
Member 961649319-Sep-14 4:16 
GeneralMy vote of 3 Pin
MostafaHelmy15-Sep-14 23:26
MostafaHelmy15-Sep-14 23:26 
Bug[My vote of 1] Poor code Pin
Ken Fogel4-Sep-14 3:29
Ken Fogel4-Sep-14 3:29 
GeneralRe: [My vote of 1] Poor code Pin
Emiliarge4-Sep-14 3:40
professionalEmiliarge4-Sep-14 3:40 
GeneralRe: [My vote of 1] Poor code Pin
Koolski5-Sep-14 7:16
Koolski5-Sep-14 7:16 
GeneralRe: [My vote of 1] Poor code Pin
Ken Fogel5-Sep-14 10:39
Ken Fogel5-Sep-14 10:39 
GeneralRe: [My vote of 1] Poor code Pin
Emiliarge5-Sep-14 12:32
professionalEmiliarge5-Sep-14 12:32 
GeneralRe: [My vote of 1] Poor code Pin
Ken Fogel5-Sep-14 15:15
Ken Fogel5-Sep-14 15:15 
GeneralRe: [My vote of 1] Poor code Pin
Emiliarge5-Sep-14 16:29
professionalEmiliarge5-Sep-14 16:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.