1. 程式人生 > >JTable寫入數據庫內容

JTable寫入數據庫內容

jframe package pri def 內容 odi create jta lex

/*
JTable中導入數據庫數據。
創建2個Vector
col和dat  col存入字段名
dat存入數據內容。
dbname=new JTable(dat,col);

*/
package demo; import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.io.*; import java.sql.*; import java.util.Vector; public class TableDemo extends JFrame { JScrollPane jsp=new JScrollPane(); JTable dbname; public TableDemo() { super("加載數據庫內容示例"); Container c=getContentPane(); c.setLayout(new BorderLayout()); ResultSetMetaData rsd=null; Vector col= new Vector(); Vector dat= new Vector(); try { Class.forName("com.mysql.jdbc.Driver"); } catch(ClassNotFoundException e1) { System.out.println("未找到相關的驅動程序!"); } try { Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?user=root&password=root&useUnicode=true&characterEncoding=UTF8"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select * from user"); rsd=rs.getMetaData(); for(int i=1;i<=rsd.getColumnCount();i++) { col.add(rsd.getColumnName(i)); } while(rs.next()) { Vector v=new Vector(); for(int i=1;i<=rsd.getColumnCount();i++) { v.addElement(rs.getString(i)); } dat.addElement(v); } st.close(); con.close(); System.out.println("數據庫加載成功!"); } catch(SQLException e2) { System.out.println("table not found!"+e2.getNextException()+"\n"+e2.getSQLState()); } dbname=new JTable(dat,col); jsp.getViewport().add(dbname); c.add(jsp); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(800,600); setVisible(true); } public static void main(String[] args) { TableDemo jst=new TableDemo(); } }

JTable寫入數據庫內容