标签:
一共有两个类:一个数据库的,一个测试的。
package com.test.table;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
/**
* table的创建
*
* @author Administrator
*
*/
public class TestTable {
private JFrame frame;
private static DefaultTableModel model;
private static JTable table;
private String[] header = { "书名", "出版号", "价格" };
private String[][] data = null;
public TestTable() {
init();
addCompont();
show();
}
private void show() {
frame.setBounds(200, 300, 300, 400);
frame.setVisible(true);
}
/**
* 添加组件
*/
private void addCompont() {
frame.add(new JScrollPane(table));
}
/**
* 实例 先选中要单独列出的方法 右键 refactor->extract Method or alt+shift+M 导入包
* ctrl+shift+o 查看快捷键 ctrl+shift+l
*/
private void init() {
frame = new JFrame("Test");
model = new DefaultTableModel(data, header);
table = new JTable(model);
table.setBorder(BorderFactory.createLineBorder(Color.BLUE));
}
public static void main(String[] args) {
new TestTable();
new DataBase().addTable(model);
}
}
---------------------------------------------------------------------------------------
package com.test.table;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.table.DefaultTableModel;
import org.junit.Test;
import com.mysql.jdbc.PreparedStatement;
/**
* 数据库操作
*
* @author Administrator
*
*/
public class DataBase {
private Connection con = null;
private PreparedStatement ps = null;
private ResultSet rs = null;
private String name;
private String id;
private String price;
private String[] data;
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("驱动加载失败");
}
}
@Test
public Connection connection() {
try {
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/book", "root", "111111");
} catch (SQLException e) {
System.out.println("数据库连接失败");
}
return con;
}
@Test
public void addTable(DefaultTableModel model) {
try {
ps = (PreparedStatement) connection().prepareStatement(
"select*from math");
rs = ps.executeQuery();
while (rs.next()) {
data = null;
name = rs.getString("name");
id = rs.getString("id");
price = rs.getString("price");
data = new String[] { name, id, price };
model.addRow(data);
}
} catch (SQLException e) {
}
}
}
-----------------------------------------
数据库及运行结果截图
标签:
原文地址:http://www.cnblogs.com/goddnessmin/p/4657514.html