Une interface pour mysql

Soyez le premier à donner votre avis sur cette source.

Snippet vu 24 896 fois - Téléchargée 30 fois

Contenu du snippet

il s'agit d'une petite interface pour MySql,, on se connecte au driver jdbc (il faut l'avoir installé auparavant...). je me suis servi du code de qqn de ce site (je ne me souviens plus de son pseudo, j'espère qu'il m'excusera si il se reconnait) pour la JTable. Il est nécessaire de bien connaitre mysql. Ce truc a été fait avec netbeans.

Source / Exemple :


/*

  • Main.java
*
  • Created on 4 février 2004, 20:42
  • /
import java.sql.*; import java.io.*; import java.util.*; import javax.swing.table.*; import javax.swing.*; import java.awt.*; public class MySql extends javax.swing.JFrame { Connection connection; /** Creates new form Main */ public MySql() { initComponents(); setSize(515,535); this.setResizable(false); } /** This method is called from within the constructor to
  • initialize the form.
  • WARNING: Do NOT modify this code. The content of this method is
  • always regenerated by the Form Editor.
  • /
private void initComponents() {//GEN-BEGIN:initComponents jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jPasswordField1 = new javax.swing.JPasswordField(); jPanel2 = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); jTextPane2 = new javax.swing.JTextPane(); jPanel3 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextPane1 = new javax.swing.JTextPane(); jButton2 = new javax.swing.JButton(); jPanel4 = new javax.swing.JPanel(); jScrollPane3 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jButton4 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); getContentPane().setLayout(null); setTitle("MySql interface"); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { exitForm(evt); } }); jPanel1.setLayout(null); jLabel1.setText("user"); jPanel1.add(jLabel1); jLabel1.setBounds(10, 10, 40, 20); jLabel2.setText("password"); jPanel1.add(jLabel2); jLabel2.setBounds(130, 10, 70, 24); jTextField1.setName("user"); jTextField1.setPreferredSize(new java.awt.Dimension(50, 25)); jPanel1.add(jTextField1); jTextField1.setBounds(50, 10, 70, 25); jButton1.setText("connect"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jPanel1.add(jButton1); jButton1.setBounds(310, 10, 90, 30); jPanel1.add(jPasswordField1); jPasswordField1.setBounds(200, 10, 100, 28); getContentPane().add(jPanel1); jPanel1.setBounds(0, 0, 410, 40); jPanel2.setLayout(new java.awt.BorderLayout()); jScrollPane2.setViewportView(jTextPane2); jPanel2.add(jScrollPane2, java.awt.BorderLayout.CENTER); getContentPane().add(jPanel2); jPanel2.setBounds(10, 70, 490, 130); jPanel3.setLayout(new java.awt.BorderLayout()); jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); jTextPane1.setText("To connect, enter your username and password"); jScrollPane1.setViewportView(jTextPane1); jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER); getContentPane().add(jPanel3); jPanel3.setBounds(10, 380, 490, 100); jButton2.setText("execute SQL"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); getContentPane().add(jButton2); jButton2.setBounds(290, 210, 110, 30); jPanel4.setLayout(new java.awt.BorderLayout()); jScrollPane3.setBorder(new javax.swing.border.MatteBorder(null)); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane3.setViewportView(jTable1); jPanel4.add(jScrollPane3, java.awt.BorderLayout.CENTER); getContentPane().add(jPanel4); jPanel4.setBounds(10, 250, 490, 120); jButton4.setText("import SQL File"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { OuvrirFichierActionPerformed(evt); } }); getContentPane().add(jButton4); jButton4.setBounds(150, 210, 140, 30); jButton3.setText("show databases"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); getContentPane().add(jButton3); jButton3.setBounds(10, 210, 140, 30); jButton5.setText("quit"); jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { quitterActionPerformed(evt); } }); getContentPane().add(jButton5); jButton5.setBounds(440, 480, 60, 30); jLabel3.setText("Write your SQL code here or import a file :"); getContentPane().add(jLabel3); jLabel3.setBounds(10, 50, 270, 24); pack(); }//GEN-END:initComponents private void quitterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_quitterActionPerformed // Add your handling code here: System.exit(0); }//GEN-LAST:event_quitterActionPerformed private void OuvrirFichierActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OuvrirFichierActionPerformed // Add your handling code here: String currentDir="."; String destination; File selected; JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); File fdir = new File(currentDir); chooser.setCurrentDirectory(fdir); if(chooser.showDialog(this,"Choisir") == JFileChooser.APPROVE_OPTION) { selected = chooser.getSelectedFile(); destination = new String(selected.getParent() + File.separatorChar + selected.getName()); currentDir = selected.getParent(); String s= lireFichier(destination); jTextPane2.setText(s); } }//GEN-LAST:event_OuvrirFichierActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed // Add your handling code here: executerSQL("show databases"); }//GEN-LAST:event_jButton3ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // Add your handling code here: try{ String query=this.jTextPane2.getSelectedText().replace( '%', '`' ); if(connection==null) ecrireOut("you have to be identified to perform this operation"); else {executerSQL(query); if (query.startsWith("drop")||query.startsWith("create")) executerSQL("show tables");} } catch(NullPointerException excep){ ecrireOut("you have to select some code to execute"); } }//GEN-LAST:event_jButton2ActionPerformed void executerSQL(String query){ // executer le sql de la fenetre if (connection==null) ecrireOut("you have to be identified to perform this operation"); try { if ( connection == null ) {System.out.println("connection==null");return;} Statement stm = connection.createStatement(); String catalog = connection.getCatalog(); String queryMaj = query.toUpperCase(); if ( ( queryMaj.trim().startsWith( "SELECT" ) ) || ( queryMaj.trim().startsWith( "DESCRIBE" ) ) || ( queryMaj.trim().startsWith( "SHOW" ) ) ) { jTable1.removeAll(); ResultSet rs = stm.executeQuery( query ); ResultSetMetaData mdt = rs.getMetaData(); int num = mdt.getColumnCount(); DefaultTableModel df = new DefaultTableModel() { public boolean isCellEditable( int row, int col ) { if ( (row>>1)<<1 == row ) return true; return false; } }; for ( int i = 0; i < num; i++ ) { df.addColumn( mdt.getColumnName( i + 1 ) ); } jTable1.setModel( df ); TableCellRenderer tbcH = createDemoHeaderRenderer(); for ( int i = 0; i < num; i++ ) { TableColumn tc = jTable1.getTableHeader().getColumnModel().getColumn( i ); tc.setHeaderRenderer( tbcH ); tc.setCellRenderer( new DemoCellRenderer() ); } int line = 0; while ( rs.next() ) { Vector v = new Vector( 10 ); for ( int col = 0; col < num; col++ ) v.addElement( rs.getString( col + 1 ) ); df.addRow( v ); line++; } jTextPane1.setText( line + " rows selected"); rs.close(); } else { ecrireOut( "SQL executer : " + query ); stm.executeUpdate( query ); } stm.close(); } catch ( Exception e ) { jTextPane1.setText( "\nError execute sql : " + e ); jTextPane1.setText( "sql : " + query ); } } void ecrireOut(String chaine){ jTextPane1.setText(chaine); } class DemoCellRenderer extends JLabel implements TableCellRenderer { boolean isBordered = true; Color selectedForeground = null; Color selectedBackground = null; Color unselectedForegroundAlt = null; Color unselectedBackgroundAlt = new Color( 200, 200, 200 ); Color unselectedForeground = null; Color unselectedBackground = null; public DemoCellRenderer() { super(); setOpaque(true); } public Component getTableCellRendererComponent( JTable table, Object val, boolean isSelected, boolean hasFocus, int row, int column) { setAlignmentX( CENTER_ALIGNMENT ); Font f = getFont(); if ( isSelected ) { setFont( new Font( f.getName(), Font.PLAIN|Font.ITALIC, f.getSize() ) ); super.setForeground( ( selectedForeground != null) ? selectedForeground : table.getSelectionForeground() ); super.setBackground( ( selectedBackground != null) ? selectedBackground : table.getSelectionBackground() ); } else { setFont( new Font( f.getName(), Font.PLAIN, f.getSize() ) ); if ( ((column)>>1)<<1 == column - (row-((row>>1)<<1)) ) { super.setForeground( ( unselectedForegroundAlt != null) ? unselectedForegroundAlt : table.getForeground() ); super.setBackground( ( unselectedBackgroundAlt != null) ? unselectedBackgroundAlt : table.getBackground() ); } else { super.setForeground( ( unselectedForeground != null) ? unselectedForeground : table.getForeground() ); super.setBackground( ( unselectedBackground != null) ? unselectedBackground : table.getBackground() ); } } setText( (String)val ); return this; } } Color foreColor = new Color( 0, 0, 50 ); Hashtable couleur = new Hashtable( 10 ); Color defoBack = new Color( 194, 194, 194); private TableCellRenderer createDemoHeaderRenderer() { DefaultTableCellRenderer label = new DefaultTableCellRenderer() { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { setText((value == null) ? "" : value.toString()); if (table != null) { JTableHeader header = table.getTableHeader(); if (header != null) { Color back = (Color)couleur.get( getText() ); setForeground( foreColor ); setBackground( (back==null)?defoBack:back ); setFont(header.getFont()); } } setBorder(UIManager.getBorder("TableHeader.cellBorder")); return this; } }; label.setHorizontalAlignment(JLabel.CENTER); return label; } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // Add your handling code here: String user=jTextField1.getText(); char[] passwd=jPasswordField1.getPassword(); connect(user,passwd); }//GEN-LAST:event_jButton1ActionPerformed public void connect(String user,char[] passwd) { String out=new String(); try { String pass = new String(passwd); if (user.compareTo("")==0) {jTextPane1.setText("Enter a valid username/password please"); return;} out="Connecting to the JDBC driver\n"; Class.forName("com.mysql.jdbc.Driver").newInstance(); out=out+"Driver com.mysql.jdbc.Driver loaded\n"; try { out=out+"Connecting to database\n"; connection = DriverManager.getConnection("jdbc:mysql://localhost/test?user="+user + "&password="+ pass); out=out+"Database connected\n"; } catch (SQLException ex) { out = out + "Your user/password is not correct, try again please"; } } catch (Exception ex) { jTextPane1.setText("Driver loading failed\n"); } jTextPane1.setText(out); } String lireFichier(String fic) { FileReader fr = null; LineNumberReader reader = null; try { fr = new FileReader(fic); reader = new LineNumberReader(fr); } catch (FileNotFoundException e) { reader = null; ecrireOut(fic+" (fichier introuvable)"); return(""); } String res = ""; String line; try { for (;;) { line = reader.readLine(); if (line == null) break; res += line+"\r\n"; } } catch (IOException e) { ecrireOut(fic+" (lecture imposible)"); } try { reader.close(); fr.close(); } catch (IOException e) { ecrireOut(fic+" (fermeture impossible)"); } reader = null; return(res); } /** Exit the Application */ private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm try { Toolkit.getDefaultToolkit().beep(); int reply = JOptionPane.showConfirmDialog(this, "Do you really want to quit?", "Interface MySql - Quit" , JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (reply == JOptionPane.YES_OPTION) { System.exit(0); } } catch (Exception e) { } }//GEN-LAST:event_exitForm /**
  • @param args the command line arguments
  • /
public static void main(String args[]) { new MySql().show(); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPasswordField jPasswordField1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JTable jTable1; private javax.swing.JTextField jTextField1; private javax.swing.JTextPane jTextPane1; private javax.swing.JTextPane jTextPane2; // End of variables declaration//GEN-END:variables }

A voir également

Ajouter un commentaire

Commentaires

begueradj
Messages postés
291
Date d'inscription
dimanche 4 octobre 2009
Statut
Membre
Dernière intervention
25 août 2014
1 -
que fait ce programme, svp ?
allomona
Messages postés
2
Date d'inscription
samedi 26 avril 2008
Statut
Membre
Dernière intervention
18 octobre 2010
-
travail agréable
darude012
Messages postés
1
Date d'inscription
vendredi 18 décembre 2009
Statut
Membre
Dernière intervention
1 février 2010
-
je te dit chapeau pour ce code source , il est très bien , moi qui chercher comment gérer la connexion a partir des fieldtext,

en plus c'est super simple a utiliser
bdina
Messages postés
2
Date d'inscription
dimanche 7 juin 2009
Statut
Membre
Dernière intervention
13 juin 2009
-
mon travaille et faite avec easyphp

et l'interface avec html
bdina
Messages postés
2
Date d'inscription
dimanche 7 juin 2009
Statut
Membre
Dernière intervention
13 juin 2009
-
moi aussi je chercher de faire une interface pour creation d'un site web qui manipule une base de donnée pour une gestion de retraités mais j'ai aucune idée.

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.