Salve a tutti,
volevo mostrarvi questo (neo) progetto:
consiste nel creare una libreria per semplificare la vita ai programmatori che devono creare applicazioni in Java utilizzandono il JDBC per collegarsi ad un database.
DatabaseJTable non è altro che una classe che estende JTable prendendo il contenuto da un database specificato.
Fornisce inoltre i metodi per aggiornare i contenuti, rimuovere/aggiungere righe, ecc.
FEATURES:
- Scrive una JTable prendendo i dati da un database MySQL: questo può essere protetto da password ma anche no.
- Permette l'aggiornamento della tabella in tutte e due le vie (prendendo i dati dalla tabella ed inserendoli nel database o viceversa).
- Permette la creazione e la rimozione di righe
- Le intestazioni delle colonne (headers) sono prese da quelle del database, il programmatore/l'utente può decidere comunque se impostarsele da sè.
TO DO:
- È sicuramente da migliorare il sistema per la sincronizzazione della tabella con il database: ogni volta vengono inviati al database tutti i campi, anche quelli non modificati
- Cliccando sui bottoni all'intestazione di ogni colonna, la tabella dovrebbe ordinarsi in ordine alfabetico crescente/decrescente (si può vare con SQL usando ORDER BY Colonna ASC/DESC).
- Implementazione di più tecnologie SQL (per il momento usa solo MySQL), magari aggiungendo anche la possibilità di usare database su file.
- Le intestazioni delle colonne (headers) sono prese da quelle del database, il programmatore/l'utente può decidere comunque se impostarsele da sè.
- La tabella non riesce a manipolare tutti i tipi di dati, im più c'è qualche piccolo problema con i BOOLEAN.
- JavaDoc e API
SORGENTI:
Last but not least...
class DatabaseJTable
- Codice: Seleziona tutto
import javax.swing.*;
import javax.swing.table.*;
import java.sql.*;
import java.util.*;
import java.text.*;
public class DatabaseJTable extends JTable{
protected static Statement stmt = null;
protected static ResultSet rs = null;
protected static ResultSetMetaData rsmd = null;
protected static DefaultTableModel tableModel = null;
protected static boolean somethingToWrite = false;
protected static int resultSetRows = 0;
protected static int resultSetColumns = 0;
protected boolean databaseHeaders = false;
protected String usedQuery = null;
public DatabaseJTable (Database db) throws SQLException{
stmt = db.getConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
}
void updateResultSet (String query) throws Exception{
resultSetRows = 1; resultSetColumns = 0;
rs = stmt.executeQuery (query);
rsmd = rs.getMetaData();
rs.first();
while (rs.next()){
resultSetRows++;
}
rs.first();
resultSetColumns = rsmd.getColumnCount();
}
void updateTable (String query, boolean columnHeadersFromDatabase) throws Exception{
usedQuery = query;
resultSetRows = 1; resultSetColumns = 0;
rs = stmt.executeQuery (query);
rsmd = rs.getMetaData();
rs.first();
while (rs.next()){
resultSetRows++;
}
rs.first();
resultSetColumns = rsmd.getColumnCount();
//COLUMN HEADERS DA DATABASE
databaseHeaders = columnHeadersFromDatabase;
if (columnHeadersFromDatabase == true){
ArrayList <String> columnHeaders = new ArrayList <String> ();
for (int i = 1; i <= resultSetColumns; i++){
columnHeaders.add (rsmd.getColumnName (i));
}
tableModel = new DefaultTableModel (columnHeaders.toArray(), resultSetRows);
}
else{
tableModel = new DefaultTableModel (resultSetRows, resultSetColumns);
}
this.setModel (tableModel);
for (int absoluteRow = 1; absoluteRow <= resultSetRows; absoluteRow++){
rs.absolute (absoluteRow);
int tableRow = absoluteRow; tableRow--;
//table.setValueAt(valore, riga, colonna)
for (int absoluteColumn = 1; absoluteColumn <= resultSetColumns; absoluteColumn++){
int tableColumn = absoluteColumn; tableColumn--;
final int COLUMN_TYPE = rsmd.getColumnType (absoluteColumn);
final String COLUMN_NAME = rsmd.getColumnName (absoluteColumn);
if (COLUMN_TYPE == Types.VARCHAR){
this.setValueAt (rs.getString(COLUMN_NAME), tableRow, tableColumn);
}
else if (COLUMN_TYPE == Types.INTEGER){
this.setValueAt (rs.getInt(COLUMN_NAME), tableRow, tableColumn);
}
else if (COLUMN_TYPE == Types.BOOLEAN){
this.setValueAt (rs.getBoolean(COLUMN_NAME), tableRow, tableColumn);
}
else if (COLUMN_TYPE == Types.FLOAT){
this.setValueAt (rs.getFloat(COLUMN_NAME), tableRow, tableColumn);
}
else if (COLUMN_TYPE == Types.DATE){
this.setValueAt (rs.getDate(COLUMN_NAME), tableRow, tableColumn);
}
else if (COLUMN_TYPE == Types.TIME){
this.setValueAt (rs.getTime(COLUMN_NAME), tableRow, tableColumn);
}
else if (COLUMN_TYPE == Types.TINYINT){
this.setValueAt (rs.getBoolean(COLUMN_NAME), tableRow, tableColumn);
}
else if (COLUMN_TYPE == Types.OTHER){
this.setValueAt (rs.getBoolean(COLUMN_NAME), tableRow, tableColumn);
}
else if (COLUMN_TYPE == Types.LONGVARCHAR){
this.setValueAt (rs.getString(COLUMN_NAME), tableRow, tableColumn);
}
else if (COLUMN_TYPE == Types.BIT){
this.setValueAt (rs.getBoolean(COLUMN_NAME), tableRow, tableColumn);
}
else{
this.setValueAt (rs.getObject(COLUMN_NAME), tableRow, tableColumn);
}
}
}
rs.first();
}
void addWhiteRow() {
ArrayList <Object> white = new ArrayList <Object> ();
for (int i = 1; i <= resultSetColumns; i++){
white.add ("");
}
tableModel.addRow(white.toArray());
this.setModel(tableModel);
somethingToWrite = true;
}
void insertData() throws Exception{
if (somethingToWrite == true){
rs.moveToInsertRow();
int rowToWrite = resultSetRows;
for (int i = 1; i <= resultSetColumns; i++){
int j = i; j--;
Object dataObject = this.getValueAt (rowToWrite, j);
final int COLUMN_TYPE = rsmd.getColumnType(i);
try{
if (COLUMN_TYPE == Types.BOOLEAN){
rs.updateBoolean (i, new Boolean(dataObject.toString()));
}
else if (COLUMN_TYPE == Types.INTEGER){
rs.updateInt (i, new Integer(dataObject.toString()));
}
else if (COLUMN_TYPE == Types.DATE){
String date = dataObject.toString();
SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd");
java.util.Date dateToParse = null;
dateToParse = sdf.parse(date);
java.sql.Date d = new java.sql.Date (dateToParse.getTime());
rs.updateDate (i, d);
}
else if (COLUMN_TYPE == Types.VARCHAR){
rs.updateString (i, dataObject.toString());
}
else {
rs.updateObject (i, dataObject);
}
}
catch (Exception e){
System.out.println ("Exception : " + e.getMessage());
}
}
rs.insertRow();
rs.moveToCurrentRow();
somethingToWrite = false;
this.updateTable(usedQuery, databaseHeaders);
}
}
void sendChanges () throws Exception{
rs.first();
for (int i = 1; i <= resultSetRows; i++){
rs.absolute (i);
int j = i; j--;
for (int k = 1; k <=resultSetColumns; k++){
int l = k; l--;
final int COLUMN_TYPE = rsmd.getColumnType(k);
final String COLUMN_NAME = rsmd.getColumnName (k);
try{
if (!this.getValueAt(j, l).toString().equals ("")){
if (COLUMN_TYPE == Types.BOOLEAN){
rs.updateBoolean (COLUMN_NAME, new Boolean(this.getValueAt (j, l).toString()));
}
else if (COLUMN_TYPE == Types.INTEGER){
rs.updateInt (COLUMN_NAME, new Integer(this.getValueAt (j, l).toString()));
}
else if (COLUMN_TYPE == Types.DATE){
String date = this.getValueAt (j, l).toString();
SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd");
java.util.Date dateToParse = null;
dateToParse = sdf.parse(date);
java.sql.Date d = new java.sql.Date (dateToParse.getTime());
rs.updateDate (COLUMN_NAME, d);
}
else if (COLUMN_TYPE == Types.VARCHAR){
rs.updateString (COLUMN_NAME, this.getValueAt (j, l).toString());
}
else {
rs.updateObject (COLUMN_NAME, this.getValueAt (j, l));
}
}
}
catch (NullPointerException npe){
System.out.println ("NullPointerException: " + npe.getMessage());
}
}
rs.updateRow();
}
rs.first();
this.updateTable(usedQuery, databaseHeaders);
}
void deleteTableRow () throws Exception{
int rowToDelete = this.getSelectedRow();
if (rowToDelete != -1){
rs.absolute (rowToDelete+1);
rs.deleteRow();
}
this.updateTable (usedQuery, databaseHeaders);
}
}
interface Database (sarebbe il collegamento al database, questa è la base per tutti i tipi a seguire)
- Codice: Seleziona tutto
import java.sql.*;
public interface Database{
public Connection connection = null;
public Connection getConnection();
public void close() throws SQLException;
}
class MySQLDatabase
- Codice: Seleziona tutto
import java.sql.*;
public class MySQLDatabase implements Database{
protected String dbName;
protected String ip;
protected String username;
protected String password;
protected Connection connection;
public MySQLDatabase (String dbName, String ip, String username, String password){
this.dbName = dbName;
this.ip = ip;
this.username = username;
this.password = password;
}
public MySQLDatabase connect() throws Exception{
Class.forName("com.mysql.jdbc.Driver");
if (!dbName.equals("")) {
if (username.equals("")) {
connection = DriverManager.getConnection("jdbc:mysql://" + ip + "/" + dbName);
}
else {
if (password.equals("")) {
connection = DriverManager.getConnection("jdbc:mysql://" + ip + "/" + dbName + "?user=" + username);
}
else {
connection = DriverManager.getConnection("jdbc:mysql://" + ip + "/" + dbName + "?user=" + username + "&password=" + password);
}
}
}
else{
throw new NullPointerException();
}
return this;
}
public Connection getConnection(){
return connection;
}
public void close() throws SQLException{
connection.close();
}
}
Esempio di utilizzo:
- Codice: Seleziona tutto
import java.sql.*;
import javax.swing.*;
import java.awt.event.*;
import java.text.*;
public class Example{
public static void main (String [] args) throws Exception{
JFrame frame = new JFrame ("DatabaseJTable");
frame.setSize (700, 500);
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
MySQLDatabase db = new MySQLDatabase("Aziendale", "localhost", "root", "13245");
db.connect();
final DatabaseJTable table = new DatabaseJTable (db);
table.updateTable ("SELECT * FROM Tabulato", true);
final JMenu menu = new JMenu ("Azioni");
final JMenuItem insertNewRow = new JMenuItem ("Inserisci riga bianca");
final JMenuItem sendNewRow = new JMenuItem ("Invia nuova riga");
final JMenuItem deleteRow = new JMenuItem ("Elimina riga");
final JMenuItem sendUpdates = new JMenuItem ("Invia aggiornamenti");
final JMenuItem updateTable = new JMenuItem ("Aggiorna tabella");
ActionListener alinsertRow = new ActionListener(){
public void actionPerformed (ActionEvent e){
table.addWhiteRow();
insertNewRow.setVisible (false);
sendNewRow.setVisible (true);
}
};
ActionListener alsendRow = new ActionListener (){
public void actionPerformed (ActionEvent e){
try{
table.insertData();
}
catch (Exception ex){
ex.printStackTrace();
}
insertNewRow.setVisible (true);
sendNewRow.setVisible (false);
}
};
ActionListener aldeleteRow = new ActionListener (){
public void actionPerformed (ActionEvent e){
try{
table.deleteTableRow();
}
catch (Exception ex){
ex.printStackTrace();
}
}
};
ActionListener alsendUpdates = new ActionListener (){
public void actionPerformed (ActionEvent e){
try{
table.sendChanges();
}
catch (Exception ex){
ex.printStackTrace();
}
}
};
ActionListener alUpdateTable = new ActionListener (){
public void actionPerformed (ActionEvent e){
try{
table.updateTable("SELECT * FROM Tabulato", true);
}
catch (Exception ex){
ex.printStackTrace();
}
}
};
insertNewRow.addActionListener (alinsertRow); sendNewRow.addActionListener (alsendRow);
deleteRow.addActionListener (aldeleteRow); sendUpdates.addActionListener (alsendUpdates);
sendNewRow.setVisible (false);
updateTable.addActionListener (alUpdateTable);
menu.add (insertNewRow); menu.add(sendNewRow); menu.add(deleteRow); menu.add (sendUpdates);menu.add (updateTable);
JMenuBar bar = new JMenuBar ();
bar.add (menu);
frame.setJMenuBar (bar);
frame.add (new JScrollPane(table));
frame.setVisible (true);
}
}
P.S.: Considerate che non è da molto che scrivo in Java, quindi suggerimenti/consigli sono sempre ben accolti.
P.P.S.: Domani se ho tempo metto tutto su sourceforge(?).
