在JAVA中從資料庫中取的值,用表格顯示

來源:互聯網
上載者:User

//列子1:簡單 import java.util.Vector; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class Table extends JFrame { private JTable table; public static void main(String args[]) { try { Table frame = new Table(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } public Table() { super(); getContentPane_r().setLayout(null); setBounds(100, 100, 500, 375); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(55, 65, 340, 174); getContentPane_r().add(scrollPane); table = new JTable(); scrollPane.setViewportView(table); // this.CreatTable(); } private void CreatTable(){ DefaultTableModel dtm = new DefaultTableModel(); Vector Title = new Vector(); //添加標題 Title.add( "姓名 "); Title.add( "性別 "); Title.add( "愛好 "); Vector c1 = new Vector(); //添加第一條內容 c1.add( "西門慶 "); c1.add( "男 "); c1.add( "SM "); Vector c2 = new Vector(); //添加第二條內容 c2.add( "潘金蓮 "); c2.add( "女 "); c2.add( "ML "); Vector Main = new Vector(); Main.add(c1); Main.add(c2); dtm.setDataVector(Main, Title); table.setModel(dtm); } } //2.列子 帶資料庫 //是串連SQLServer的pubs資料庫的authors表的.我用odbc驅動,資料來源是pubs. import javax.swing.*; import java.sql.*; class SqlDemo2 extends JFrame{ SqlDemo2(){ try{ String[] colHeads={ "name ", "Phone ", "City "}; Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver "); String url= "jdbc:odbc:pubs "; Connection con=DriverManager. getConnection_r(url, "sa ", " "); Statement stmt=con.createStatement(); ResultSet rs; rs=stmt.executeQuery( "SELECT count(*) as au_count from authors "); rs.next(); int iCount=rs. getInt_r( "au_count "); Object[][] data=new Object[iCount][]; int i=0; rs=stmt.executeQuery( "SELECT * from authors "); while(rs.next()){ data[i]=new Object[3]; data[i][0]=rs. getString_r( "au_fname "); data[i][1]=rs. getString_r( "Phone "); data[i][2]=rs. getString_r( "City "); i++; } JTable table=new JTable(data,colHeads); JScrollPane jsp=new JScrollPane(table); this. getContentPane_r().add(jsp); this.setDefaultCloseOperation(EXIT_ON_CLOSE); } catch(Exception e){ System.out.println(e); } } public static void main(String[] args){ SqlDemo2 sd=new SqlDemo2(); sd.setSize(400,250); sd.setVisible(true); } }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.