import java.sql.*;java
import java.awt.*;sql
import javax.swing.*;數據庫
import javax.swing.table.*;數組
//import java.awt.event.*;函數
public class DisplayDemo extends JFramesqlserver
//implements ActionListenerthis
{server
// private String對象
dbURL="jdbc:microsoft:sqlserver://202.115.26.181:1433"; // 數據庫標識名get
private String user="devon"; // 數據庫用戶
private String password="book"; // 數據庫用戶密碼
private JTable table;
private JButton ok,canel;
public DisplayDemo(){
super("顯示數據庫查詢結果"); //調用父類構造函數
String[] columnNames={"用戶名","年齡","性別","Email"}; //列名 Object[][] rowData=new Object[5][4]; //表格數據
ok=new JButton("肯定");
canel=new JButton("取消");
// ok.addActionListener(this);
// canel.addActionListener(this);
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:example","sa",""); // Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); //加載驅動器
// Connection con=DriverManager.getConnection(dbURL,user,password); //獲取鏈接
String sqlStr="select * from users"; //查詢語句
PreparedStatement ps=con.prepareStatement(sqlStr); //獲取PreparedStatement對象
ResultSet rs=ps.executeQuery(); //執行查詢
String name,sex,email; //查詢結果
int age;
int count=0;
while (rs.next()){ //遍歷查詢結果
rowData[count][0]=rs.getString("name"); //初始化數組內容 rowData[count][1]=Integer.toString(rs.getInt("age"));
rowData[count][2]=rs.getString("sex");
rowData[count][3]=rs.getString("email");
count++;
}
con.close(); //關閉鏈接
}
catch(Exception ex){
ex.printStackTrace(); //輸出出錯信息
}
Container container=getContentPane(); //獲取窗口容器
//container.setLayout(null);
container.add(ok);container.add(canel);
ok.setBounds(10,120,70,20);
canel.setBounds(100,120,70,20);
table=new JTable(rowData,columnNames); //實例化表格
table.getColumn("年齡").setMaxWidth(25); //設置行寬
container.add(new JScrollPane(table),BorderLayout.CENTER); //增長組件
setSize(300,200); //設置窗口尺寸
setVisible(true); //設置窗口可視
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //關閉窗口時退出程序
}
public static void main(String[] args){
new DisplayDemo();
}
}