/*
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();
}
}