public void actionPerformed(ActionEvent evt) { // 删除原来的JTable(JTable使用scrollPane来包装) if (scrollPane != null) { jf.remove(scrollPane); } try ( // 根据用户输入的SQL执行查询 ResultSet rs = stmt.executeQuery(sqlField.getText())) { // 取出ResultSet的MetaData ResultSetMetaData rsmd = rs.getMetaData(); Vector<String> columnNames = new Vector<>(); Vector<Vector<String>> data = new Vector<>(); // 把ResultSet的所有列名添加到Vector里 for (int i = 0; i < rsmd.getColumnCount(); i++) { columnNames.add(rsmd.getColumnName(i + 1)); } // 把ResultSet的所有记录添加到Vector里 while (rs.next()) { Vector<String> v = new Vector<>(); for (int i = 0; i < rsmd.getColumnCount(); i++) { v.add(rs.getString(i + 1)); } data.add(v); } // 创建新的JTable JTable table = new JTable(data, columnNames); scrollPane = new JScrollPane(table); // 添加新的Table jf.add(scrollPane); // 更新主窗口 jf.validate(); } catch (Exception e) { e.printStackTrace(); } }
public void setQuery(String q) { cache = new Vector(); try { ResultSet rs = statement.executeQuery(q); ResultSetMetaData meta = rs.getMetaData(); colCount = meta.getColumnCount(); headers = new String[colCount]; for (int h = 1; h <= colCount; h++) { headers[h - 1] = meta.getColumnName(h); } while (rs.next()) { String[] record = new String[colCount]; for (int i = 0; i < colCount; i++) { record[i] = rs.getString(i + 1); } cache.addElement(record); } // while sonu fireTableChanged(null); } // try sonu catch (Exception e) { cache = new Vector(); e.printStackTrace(); } } // setQuery sonu
public boolean dbOpenList(Connection connection, String sql) { dbClearList(); this.oldSql = sql; this.oldConnection = connection; // apre il resultset da abbinare ResultSet resu = null; ResultSetMetaData meta; try { stat = connection.createStatement(); resu = stat.executeQuery(sql); meta = resu.getMetaData(); if (meta.getColumnCount() > 1) { this.contieneChiavi = true; } // righe while (resu.next()) { for (int i = 1; i <= meta.getColumnCount(); ++i) { if (i == 1) { dbItems.add((Object) resu.getString(i)); lm.addElement((Object) resu.getString(i)); } else if (i == 2) { dbItemsK.add((Object) resu.getString(i)); // debug // System.out.println("list:" + String.valueOf(i) + ":" + resu.getString(i)); } else if (i == 3) { dbItemsK2.add((Object) resu.getString(i)); } } } this.setModel(lm); // vado al primo if (dbTextAbbinato != null) { // debug // javax.swing.JOptionPane.showMessageDialog(null,this.getKey(0).toString()); dbTextAbbinato.setText(this.getKey(0).toString()); } return (true); } catch (Exception e) { javax.swing.JOptionPane.showMessageDialog(null, e.toString()); e.printStackTrace(); return (false); } finally { try { stat.close(); } catch (Exception e) { } try { resu.close(); } catch (Exception e) { } meta = null; } }
public void setJenis() { dataJenis = new ArrayList<Jenis>(); try { String qry = "SELECT * from jenis"; ResultSet rs = stm.executeQuery(qry); while (rs.next()) { Jenis j = new Jenis(); j.setIdJenis(rs.getInt("id_jenis")); j.setNamaJenis(rs.getString("nama_jenis")); dataJenis.add(j); } } catch (SQLException SQLerr) { SQLerr.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
public void tableChanged(TableModelEvent tme) { int baris = tme.getFirstRow(); int kolom = tme.getColumn(); TableModel model = (TableModel) tme.getSource(); int id = (Integer) model.getValueAt(baris, 0); String query = ""; switch (kolom) { case 1: String nama = (String) model.getValueAt(baris, kolom); query = "UPDATE produk SET nama_produk='" + nama + "' WHERE id_produk=" + id; prosesEdit(query); break; case 2: String jenis = (String) model.getValueAt(baris, kolom); try { query = "select * from jenis where nama_jenis='" + jenis + "'"; ResultSet rs = stm.executeQuery(query); if (rs.next()) { int idJenis = rs.getInt("id_jenis"); query = "UPDATE produk SET id_jenis=" + idJenis + " WHERE id_produk=" + id; prosesEdit(query); } else { setDataTabel(); JOptionPane.showMessageDialog(null, "gagal,jenis tidak ada"); } } catch (SQLException SQLerr) { SQLerr.printStackTrace(); } break; case 3: int stok = (Integer) model.getValueAt(baris, kolom); query = "UPDATE `stok_produk` SET stok=" + stok + " WHERE id_produk=" + id; prosesEdit(query); break; case 4: int harga = (Integer) model.getValueAt(baris, kolom); query = "UPDATE produk SET harga=" + harga + " WHERE id_produk=" + id; prosesEdit(query); break; case 5: String suplier = (String) model.getValueAt(baris, kolom); try { query = "SELECT * FROM suplier WHERE nama_suplier='" + suplier + "'"; ResultSet rs = stm.executeQuery(query); if (rs.next()) { int idSuplier = rs.getInt("id_suplier"); query = "UPDATE produk SET id_suplier=" + idSuplier + " WHERE id_produk=" + id; prosesEdit(query); } else { setDataTabel(); JOptionPane.showMessageDialog(null, "gagal,suplier belum terdaftar"); } } catch (SQLException SQLerr) { SQLerr.printStackTrace(); } break; default: break; } }
// ambil data dari database untuk tabel public void setDataTabel() { // combobox jenis JComboBox cbJenis = new JComboBox(); cbJenis.setModel(new DefaultComboBoxModel(dataJenis.toArray())); dataProduk = new ArrayList<Produk>(); try { String qry = "SELECT * FROM produk,suplier,jenis,stok_produk WHERE produk.id_jenis = jenis.id_jenis AND produk.id_suplier = suplier.id_suplier AND produk.id_produk=stok_produk.id_produk"; ResultSet rs = stm.executeQuery(qry); while (rs.next()) { Produk p = new Produk(); p.setIdProduk(rs.getInt("id_produk")); p.setNamaProduk(rs.getString("nama_produk")); p.setJenis(rs.getString("nama_jenis")); p.setHarga(rs.getInt("harga")); p.setStok(rs.getInt("stok")); p.setNamaSuplier(rs.getString("nama_suplier")); p.setComboJenis(cbJenis); dataProduk.add(p); } } catch (Exception err) { err.printStackTrace(); } model = new TableModelProduk(dataProduk); tabel.setModel(model); tabel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); class EditProdukListener implements TableModelListener { public void tableChanged(TableModelEvent tme) { int baris = tme.getFirstRow(); int kolom = tme.getColumn(); TableModel model = (TableModel) tme.getSource(); int id = (Integer) model.getValueAt(baris, 0); String query = ""; switch (kolom) { case 1: String nama = (String) model.getValueAt(baris, kolom); query = "UPDATE produk SET nama_produk='" + nama + "' WHERE id_produk=" + id; prosesEdit(query); break; case 2: String jenis = (String) model.getValueAt(baris, kolom); try { query = "select * from jenis where nama_jenis='" + jenis + "'"; ResultSet rs = stm.executeQuery(query); if (rs.next()) { int idJenis = rs.getInt("id_jenis"); query = "UPDATE produk SET id_jenis=" + idJenis + " WHERE id_produk=" + id; prosesEdit(query); } else { setDataTabel(); JOptionPane.showMessageDialog(null, "gagal,jenis tidak ada"); } } catch (SQLException SQLerr) { SQLerr.printStackTrace(); } break; case 3: int stok = (Integer) model.getValueAt(baris, kolom); query = "UPDATE `stok_produk` SET stok=" + stok + " WHERE id_produk=" + id; prosesEdit(query); break; case 4: int harga = (Integer) model.getValueAt(baris, kolom); query = "UPDATE produk SET harga=" + harga + " WHERE id_produk=" + id; prosesEdit(query); break; case 5: String suplier = (String) model.getValueAt(baris, kolom); try { query = "SELECT * FROM suplier WHERE nama_suplier='" + suplier + "'"; ResultSet rs = stm.executeQuery(query); if (rs.next()) { int idSuplier = rs.getInt("id_suplier"); query = "UPDATE produk SET id_suplier=" + idSuplier + " WHERE id_produk=" + id; prosesEdit(query); } else { setDataTabel(); JOptionPane.showMessageDialog(null, "gagal,suplier belum terdaftar"); } } catch (SQLException SQLerr) { SQLerr.printStackTrace(); } break; default: break; } } private void prosesEdit(String query) { try { int hasil = stm.executeUpdate(query); if (hasil == 1) { setDataTabel(); JOptionPane.showMessageDialog(null, "edit berhasil"); } else { JOptionPane.showMessageDialog(null, "gagal"); } } catch (SQLException SQLerr) { SQLerr.printStackTrace(); } } } model.addTableModelListener(new EditProdukListener()); }
public void setContent(String cat) { cat = cat.trim(); selectAllCB.setVisible(false); selectAllCB.setSelected(false); deleteBut.setVisible(false); restoreBut.setVisible(false); refreshBut.setVisible(true); Object columns[] = null; int count = 0; switch (cat) { case "Inbox": columns = new Object[] {"", "From", "Date", "Subject", "Content"}; count = Database.getCount("Inbox"); workingSet = db.getData("SELECT * FROM messages WHERE tag='inbox' ORDER BY msg_id desc"); ; break; case "SentMail": columns = new Object[] {"", "To", "Date", "Subject", "Content"}; count = Database.getCount("Sentmail"); workingSet = db.getData("SELECT * FROM messages WHERE tag='sentmail' ORDER BY msg_id desc"); break; case "Draft": columns = new Object[] {"", "To", "Date", "Subject", "Content"}; count = Database.getCount("Draft"); workingSet = db.getData("SELECT * FROM messages WHERE tag='draft' ORDER BY msg_id desc"); break; case "Outbox": columns = new Object[] {"", "To", "Date", "Subject", "Content"}; count = Database.getCount("Outbox"); workingSet = db.getData("SELECT * FROM messages WHERE tag='outbox' ORDER BY msg_id desc"); break; case "Trash": // restoreBut.setVisible(true); columns = new Object[] {"", "To/From", "Date", "Subject", "Content"}; count = Database.getCount("Trash"); workingSet = db.getData( "SELECT * FROM messages,trash WHERE messages.tag='trash' and messages.msg_id=trash.msg_id ORDER BY deleted_at desc"); break; default: System.out.println("in default case"); } if (count > 0) { selectAllCB.setVisible(true); rows = new Object[count][]; msgID = new int[count]; try { workingSet.beforeFirst(); for (int i = 0; i < count && workingSet.next(); i++) { msgID[i] = workingSet.getInt(1); rows[i] = new Object[] { false, workingSet.getString(2), workingSet.getDate(3), workingSet.getString(4), workingSet.getString(5) }; } } catch (SQLException sqlExc) { JOptionPane.showMessageDialog(null, sqlExc, "EXCEPTION", JOptionPane.ERROR_MESSAGE); sqlExc.printStackTrace(); } tableModel = new MyDefaultTableModel(rows, columns); table = new JTable(tableModel); table.getSelectionModel().addListSelectionListener(this); table.addMouseListener(this); table.getTableHeader().setOpaque(true); table.getTableHeader().setReorderingAllowed(false); // table.getTableHeader().setBackground(Color.blue); table.getTableHeader().setForeground(Color.blue); // table.setRowSelectionAllowed(false); // table.setColumnSelectionAllowed(false); table.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 14)); table.setRowHeight(20); table.setFillsViewportHeight(true); TableColumn column = null; for (int i = 0; i < 5; i++) { column = table.getColumnModel().getColumn(i); if (i == 0) { column.setPreferredWidth(6); } else if (i == 3) { column.setPreferredWidth(250); } else if (i == 4) { column.setPreferredWidth(450); } else { column.setPreferredWidth(40); } } table.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS); remove(contentPan); contentPan = new JScrollPane(table); contentPan.setBackground(Color.orange); contentPan.setOpaque(true); contentPan.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); add(contentPan, "Center"); Home.home.homeFrame.setVisible(true); } else { JPanel centPan = new JPanel(new GridBagLayout()); centPan.setBackground(new Color(52, 86, 70)); JLabel label = new JLabel("No Messages In This Category"); label.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 22)); label.setForeground(Color.orange); centPan.add(label); remove(contentPan); contentPan = new JScrollPane(centPan); contentPan.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); add(contentPan, "Center"); contentPan.repaint(); } }
disptable(ResultSet k) { super("PATIENT DATA"); String[] chd = { "Date: ", "Patient ID:", "Name: ", "Gender: ", "Age: ", "Weight: ", "Address: ", "Contact No.: ", "Doctor Name: ", "Symptoms: ", "Dignosis: ", "Fee: Rs.", "Blood Group" }; // DefaultTableModel dtm=new DefaultTableModel(); // jt.setModel(new DefaultTableModel(arr,chd)); jt = new JTable(); jsp = new JScrollPane(jt); btn = new JButton("CLOSE"); btn.addActionListener(this); int i = 0; try { while (k.next()) { arr[i][0] = k.getString(1); // System.out.println("ddddddddddddd"+arr[i][0]); arr[i][1] = "" + k.getInt(2); arr[i][2] = k.getString(3) + " " + k.getString(4) + " " + k.getString(5); arr[i][3] = k.getString(6); arr[i][4] = "" + k.getInt(7); arr[i][5] = k.getString(8); arr[i][6] = k.getString(9); arr[i][7] = k.getString(10); arr[i][8] = k.getString(11); arr[i][9] = k.getString(12); arr[i][10] = k.getString(13); arr[i][11] = "" + k.getInt(14); arr[i][12] = k.getString(15); arr[i][13] = k.getString(17); // dtm.insertRow(i,new Object[]{patient.rs.getString(1), // patient.rs.getInt(2),patient.rs.getString(3)+patient.rs.getString(4)+patient.rs.getString(5),patient.rs.getString(6),patient.rs.getInt(7),patient.rs.getString(8),patient.rs.getString(9),patient.rs.getString(10),patient.rs.getString(11),patient.rs.getString(12),patient.rs.getString(13),patient.rs.getInt(14)}); i++; } } catch (Exception e9) { System.out.println("" + e9); } jt.setModel(new DefaultTableModel(arr, chd)); Container con = getContentPane(); con.setLayout(null); jsp.setBounds(20, 20, 1230, 600); btn.setBounds(685, 630, 100, 30); add(jsp); add(btn); setSize(1330, 800); setVisible(true); }
public static boolean psearch(int n) throws Exception { pps.setInt(1, n); rs = pps.executeQuery(); return rs.next(); }
private void Baru() { btnSave.setText("Save"); txtNip.requestFocus(); txtNip.setText(""); try { Class.forName(KoneksiDatabase.driver); java.sql.Connection c = DriverManager.getConnection( KoneksiDatabase.database, KoneksiDatabase.user, KoneksiDatabase.pass); Statement s = c.createStatement(); String sql = "select * from absensi_lembur"; ResultSet rs = s.executeQuery(sql); final String[] headers = { "Kd Absen", "NIP", "Tgl Absen", "Masuk", "Pulang", "Hari", "Tipe Hari", "Terlambat", "Lembur", "Tipe Lembur", "Tot Lembur", "Tunj Makan", "Tunj Transport" }; rs.last(); int n = rs.getRow(); Object[][] data = new Object[n][13]; int p = 0; rs.beforeFirst(); while (rs.next()) { data[p][0] = rs.getString(1); data[p][1] = rs.getString(2); data[p][2] = rs.getString(3); data[p][3] = rs.getString(4); data[p][4] = rs.getString(5); data[p][5] = rs.getString(6); data[p][6] = rs.getString(7); data[p][7] = rs.getString(8); data[p][8] = rs.getString(9); data[p][9] = rs.getString(10); data[p][10] = rs.getString(11); data[p][11] = rs.getString(12); data[p][12] = rs.getString(13); p++; } tblLembur.setModel(new DefaultTableModel(data, headers)); tblLembur.setAlignmentX(CENTER_ALIGNMENT); } catch (Exception e) { JOptionPane.showMessageDialog( null, "Gagal Koneksi, Ada Kesalahan.", "Warning", JOptionPane.WARNING_MESSAGE); } }
public ItensVendidos() { super("Itens Vendidos"); JButton imprimir; final DefaultTableModel modelo = new DefaultTableModel(); // constrói a tabela JTable tabela = new JTable(modelo); // Cria duas colunas modelo.addColumn("Código"); modelo.addColumn("Vendedor"); modelo.addColumn("Produto"); modelo.addColumn("Quantidade"); imprimir = new JButton("Imprimir"); imprimir.setBounds(100, 450, 30, 24); // exibe os dados da tabela MySQL // Conexao banco = new Conexao(); String retorno = "erro"; try { // Connection ExConn = (Connection) banco.abrirBDconn(); Class.forName("com.mysql.jdbc.Driver"); Connection conexao = DriverManager.getConnection("jdbc:mysql://localhost/banco", "root", ""); Statement stmt = conexao.createStatement(); // procedimentos para obter os dados de uma tabela String query = "SELECT * FROM venda2"; ResultSet rs = stmt.executeQuery(query); while (rs.next()) { int id = rs.getInt("idVendedor"); String nome = rs.getString("nomeVendedor"); String produto = rs.getString("produto"); int qtd = rs.getInt("qtd"); modelo.addRow(new Object[] {new Integer(id), nome, produto, new Integer(qtd)}); } // fim procedimento para obter os dados } catch (SQLException ex) { System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); } catch (Exception e) { System.out.println("Problemas ao tentar conectar com o banco de dados"); } // fim MySQL tabela.setPreferredScrollableViewportSize(new Dimension(350, 50)); Container c = getContentPane(); c.setLayout(new FlowLayout()); JScrollPane scrollPane = new JScrollPane(tabela); c.add(scrollPane); c.add(imprimir); setSize(400, 300); setVisible(true); }
public RAJ5(String sAno) { int files; int cols; String query11 = "drop table if exists tempAJ5 "; String query22 = "drop table if exists tempAJ5a "; String query1 = "create table tempAJ5 "; query1 += "select ano,descripcion as oficina,materia,sum(num) as num "; query1 += "from asist_juridica,oficinas "; query1 += "where (ano=\"" + sAno + "\") and (asist_juridica.oficina=oficinas.codigo) "; query1 += "group by materia,oficina "; query1 += "order by materia"; String query2 = "CREATE TABLE `tempAJ5a` ( "; query2 += "`ano` char(4) default '0', "; query2 += "`materia` char(15) default '0', "; query2 += "`of_benassal` int(3) unsigned default '0', "; query2 += "`of_montanejos` int(3) unsigned default '0', "; query2 += "`of_morella` int(3) unsigned default '0', "; query2 += "`of_onda` int(3) unsigned default '0', "; query2 += "`of_segorbe` int(3) unsigned default '0', "; query2 += "`of_traiguera` int(3) unsigned default '0'"; query2 += ") "; String query3 = "Select * from tipo_asist_jur"; String query4 = "select * from tempAJ5"; try { Connection con = this.getConnection(); Statement sentencia11 = con.createStatement(); sentencia11.execute(query11); sentencia11.close(); Statement sentencia22 = con.createStatement(); sentencia22.execute(query22); sentencia22.close(); Statement sentencia1 = con.createStatement(); sentencia1.execute(query1); sentencia1.close(); Statement sentencia2 = con.createStatement(); sentencia2.execute(query2); sentencia2.close(); Statement sentencia3 = con.createStatement(); ResultSet rs3 = sentencia3.executeQuery(query3); Statement sentencia4 = con.createStatement(); ResultSet rs4 = sentencia4.executeQuery(query4); String query5 = ""; String materia = ""; int quantitat, quantitat1, quantitat2, quantitat3, quantitat4, quantitat5, quantitat6; while (rs3.next()) { materia = rs3.getString("abreviatura"); quantitat = 0; quantitat1 = 0; quantitat2 = 0; quantitat3 = 0; quantitat4 = 0; quantitat5 = 0; quantitat6 = 0; while (rs4.next()) { if (materia.equals(rs4.getString("materia"))) { quantitat = rs4.getInt("num"); if (rs4.getString("oficina").equals("OF. BENASAL")) { quantitat1 = quantitat; } else if (rs4.getString("oficina").equals("OF. MONTANEJOS")) { quantitat2 = quantitat; } else if (rs4.getString("oficina").equals("OF. MORELLA")) { quantitat3 = quantitat; } else if (rs4.getString("oficina").equals("OF. ONDA")) { quantitat4 = quantitat; } else if (rs4.getString("oficina").equals("OF. SEGORBE")) { quantitat5 = quantitat; } else if (rs4.getString("oficina").equals("OF. TRAIGUERA")) { quantitat6 = quantitat; } } } query5 = "insert into tempAJ5a values (\"" + sAno + "\",\"" + materia + "\"," + quantitat1 + "," + quantitat2 + "," + quantitat3 + "," + quantitat4 + "," + quantitat5 + "," + quantitat6 + ")"; Statement sentencia5 = con.createStatement(); sentencia5.execute(query5); sentencia5.close(); rs4.beforeFirst(); } sentencia3.close(); sentencia4.close(); // select final per a formar la matriu AbstractTableModel String query6 = "select *,sum(of_traiguera+of_benassal+of_morella+of_onda+of_segorbe+of_montanejos)as total "; query6 += "from tempAJ5a "; query6 += "group by materia"; Statement sentencia6 = con.createStatement(); ResultSet rs6 = sentencia6.executeQuery(query6); ResultSetMetaData rsmd6 = rs6.getMetaData(); files = 0; while (rs6.next()) { files++; } cols = rsmd6.getColumnCount(); f = new Object[files][cols]; c = new Object[cols]; for (int i = 0; i < cols; i++) { c[i] = rsmd6.getColumnName(i + 1); } int x = 0; rs6.beforeFirst(); while (rs6.next()) { for (int y = 0; y < cols; y++) { if ((y >= 2) && (y <= 8)) { f[x][y] = new Integer(rs6.getString(y + 1)); } else { f[x][y] = rs6.getString(y + 1); } } x++; } sentencia6.close(); con.close(); } catch (SQLException e) { System.err.println("Error en la base de dades: " + e); } }