1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89 |
import java.awt.BorderLayout;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
class MySQLTable
{
private static Connection con = null;
private static String URL = "jdbc:mysql://serverHostName/DBName";
private static String driver = "com.mysql.jdbc.Driver";
private static String user = "DBUserName";
private static String pass = "DBUserPassword";
public static void main(String[] args) throws SQLException
{
Statement stmt;
String query;
ResultSet rs;
Object rowData[][] = {{"Row1-Column1", "Row1-Column2", "Row1-Column3"}};
Object columnNames[] = {"Column One", "Column Two", "Column Three"};
DefaultTableModel mTableModel = new DefaultTableModel(rowData, columnNames);
JTable table = new JTable(mTableModel);
try {
Class.forName(driver).newInstance();
con = DriverManager.getConnection(URL, user, pass);
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
}
query = "SELECT colOne, colTwo, colThree FROM tableName";
stmt = con.createStatement();
rs = stmt.executeQuery(query);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
mTableModel.removeRow(0);
Object[] rows;
while (rs.next()) {
rows = new Object[]{rs.getString(1), rs.getString(2), rs.getString(3)};
mTableModel.addRow(rows);
}
}
private MySQLTable()
{
}
} |