Probleme pour fermer une connection sur un serveur sql
Bonjour,
j'ai un soucis car je n'arrive pas à savoir comment m'y prendre pour fermer la connection
lorsque l'on clique sur la "croix".
Voici le code que j'ai :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
public class Test{
public static void main(String[] args){
Frame frame = new Frame();
String[] titres = {"NOM", "PRENOM", "ADRESSE","AGE"};
MyTableModel maTable = new MyTableModel(titres);
JTable jTable = new JTable(maTable);
List<Object[]> donnees = new ArrayList<Object[]>();
//Parametre de connexion a la base de données
String url = "jdbc:sqlserver://database:1253;databaseName=MaTable";
String login = "root";
String password = "root";
final Connection connection = null;
ImprimerTable imp = new ImprimerTable(maTable, jTable);
JScrollPane scroll = new JScrollPane(imp);
frame.setSize(600,250);
frame.add(scroll);
frame.setVisible(true);
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
try{
connection.close();
}catch(SQLException se){
se.printStackTrace();
}
}
} );;
try{
while(true){
maTable.vide();
Driver monDriver = new SQLServerDriver();
DriverManager.registerDriver(monDriver);
connection=DriverManager.getConnection(url,login,password);
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql =
"SELECT * FROM MaTable";
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
int ncols = rsmd.getColumnCount();
//Remise du curseur à sa position initiale
rs.beforeFirst();
boolean suivant = rs.next();
while(suivant){
Object val [] = new Object[ncols];
for(int j=1; j<=ncols; j++)
val[j-1] = rs.getString(j);
donnees.add(val);
suivant = rs.next();
}
((MyTableModel)jTable.getModel()).remplie(donnees);
//Remise du curseur à sa position initiale
rs.beforeFirst();
try {
Thread.sleep(20000);
}catch(InterruptedException ie){
ie.printStackTrace();
connection.close();
}
}
}catch(Exception e){
e.printStackTrace();
}
} |
Au départ, je n'avais pas mis Connection comme final et ça me mettait une exception dans la méthode WindowClosing.
Maitenant que j'ai ajouté final, j'obtiens :
Code:
The final local variable connection cannot be assigned. It must be blank and not using a compound assignment
C'est la ligne suivante :
Code:
connection=DriverManager.getConnection(url,login,password);
Une solution pour résoudre ce soucis ?
Merci