我正在学习如何连接到数据库,作为一个项目,我正在制作一个JTable显示数据库信息。我正在使用一个名为world的数据库,该数据库有一个名为city的表,其中包含列id,名称,国家代码,区域,人口。这是我的代码,我在查看了java doc和其他各种来源之后编写了代码,但我不确定我是否做得对,而且我之前从未使用过向量。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
public class JTableTest extends JFrame {
Vector<String> columnNames;
Vector<Object> row;
JTable table;
public static void main(String[] args) {
JTableTest test = new JTableTest();
test.connectDB();
}
public void buildGui() {
setSize(500, 600);
setVisible(true);
JScrollPane scrollPane = new JScrollPane(table,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
getContentPane().add(scrollPane);
}
public void connectDB() {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/world";
String user = "root";
String pass = "root";
String sql = "Select id, name, countrycode, district, population from city where id < 100";
Connection conn;
Statement stmt;
ResultSet rs;
try {
Class.forName(driver);
System.out.println("connecting..");
conn = DriverManager.getConnection(url, user, pass);
System.out.println("connected!");
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
table = new JTable(rsToTableModel(rs));
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public TableModel rsToTableModel(ResultSet rs) {
try {
ResultSetMetaData md = rs.getMetaData();
int numberOfColumns = md.getColumnCount();
columnNames = new Vector<String>();
for (int i = 1; i < numberOfColumns; i++) {
columnNames.addElement(md.getColumnLabel(i));
}
row = new Vector<Object>();
while (rs.next()) {
for (int i = 1; i < numberOfColumns; i++) {
row.addElement(rs.getObject(i));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return new DefaultTableModel(row, columnNames);
}
}
这是我的错误
connecting..
connected!
[1, Kabul, AFG, Kabol, 2, Qandahar, AFG, Qandahar, 3, Herat, AFG, Herat, 4, Mazar-e-Sharif, AFG, Balkh, 5, Amsterdam, NLD, Noord-Holland, 6, Rotterdam, NLD, Zuid-Holland, 7, Haag, NLD, Zuid-Holland, 8, Utrecht, NLD, Utrecht, 9, Eindhoven, NLD, Noord-Brabant, 10, Tilburg, NLD, Noord-Brabant, 11, Groningen, NLD, Groningen, 12, Breda, NLD, Noord-Brabant, 13, Apeldoorn, NLD, Gelderland, 14, Nijmegen, NLD, Gelderland, 15, Enschede, NLD, Overijssel, 16, Haarlem, NLD, Noord-Holland, 17, Almere, NLD, Flevoland, 18, Arnhem, NLD, Gelderland, 19, Zaanstad, NLD, Noord-Holland, 20, ´s-Hertogenbosch, NLD, Noord-Brabant, 21, Amersfoort, NLD, Utrecht, 22, Maastricht, NLD, Limburg, 23, Dordrecht, NLD, Zuid-Holland, 24, Leiden, NLD, Zuid-Holland, 25, Haarlemmermeer, NLD, Noord-Holland, 26, Zoetermeer, NLD, Zuid-Holland, 27, Emmen, NLD, Drenthe, 28, Zwolle, NLD, Overijssel, 29, Ede, NLD, Gelderland, 30, Delft, NLD, Zuid-Holland, 31, Heerlen, NLD, Limburg, 32, Alkmaar, NLD, Noord-Holland, 33, Willemstad, ANT, Curaçao, 34, Tirana, ALB, Tirana, 35, Alger, DZA, Alger, 36, Oran, DZA, Oran, 37, Constantine, DZA, Constantine, 38, Annaba, DZA, Annaba, 39, Batna, DZA, Batna, 40, Sétif, DZA, Sétif, 41, Sidi Bel Abbès, DZA, Sidi Bel Abbès, 42, Skikda, DZA, Skikda, 43, Biskra, DZA, Biskra, 44, Blida (el-Boulaida), DZA, Blida, 45, Béjaïa, DZA, Béjaïa, 46, Mostaganem, DZA, Mostaganem, 47, Tébessa, DZA, Tébessa, 48, Tlemcen (Tilimsen), DZA, Tlemcen, 49, Béchar, DZA, Béchar, 50, Tiaret, DZA, Tiaret, 51, Ech-Chleff (el-Asnam), DZA, Chlef, 52, Ghardaïa, DZA, Ghardaïa, 53, Tafuna, ASM, Tutuila, 54, Fagatogo, ASM, Tutuila, 55, Andorra la Vella, AND, Andorra la Vella, 56, Luanda, AGO, Luanda, 57, Huambo, AGO, Huambo, 58, Lobito, AGO, Benguela, 59, Benguela, AGO, Benguela, 60, Namibe, AGO, Namibe, 61, South Hill, AIA, –, 62, The Valley, AIA, –, 63, Saint John´s, ATG, St John, 64, Dubai, ARE, Dubai, 65, Abu Dhabi, ARE, Abu Dhabi, 66, Sharja, ARE, Sharja, 67, al-Ayn, ARE, Abu Dhabi, 68, Ajman, ARE, Ajman, 69, Buenos Aires, ARG, Distrito Federal, 70, La Matanza, ARG, Buenos Aires, 71, Córdoba, ARG, Córdoba, 72, Rosario, ARG, Santa Fé, 73, Lomas de Zamora, ARG, Buenos Aires, 74, Quilmes, ARG, Buenos Aires, 75, Almirante Brown, ARG, Buenos Aires, 76, La Plata, ARG, Buenos Aires, 77, Mar del Plata, ARG, Buenos Aires, 78, San Miguel de Tucumán, ARG, Tucumán, 79, Lanús, ARG, Buenos Aires, 80, Merlo, ARG, Buenos Aires, 81, General San MartÃn, ARG, Buenos Aires, 82, Salta, ARG, Salta, 83, Moreno, ARG, Buenos Aires, 84, Santa Fé, ARG, Santa Fé, 85, Avellaneda, ARG, Buenos Aires, 86, Tres de Febrero, ARG, Buenos Aires, 87, Morón, ARG, Buenos Aires, 88, Florencio Varela, ARG, Buenos Aires, 89, San Isidro, ARG, Buenos Aires, 90, Tigre, ARG, Buenos Aires, 91, Malvinas Argentinas, ARG, Buenos Aires, 92, Vicente López, ARG, Buenos Aires, 93, Berazategui, ARG, Buenos Aires, 94, Corrientes, ARG, Corrientes, 95, San Miguel, ARG, Buenos Aires, 96, BahÃa Blanca, ARG, Buenos Aires, 97, Esteban EcheverrÃa, ARG, Buenos Aires, 98, Resistencia, ARG, Chaco, 99, José C. Paz, ARG, Buenos Aires]
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.Vector
at javax.swing.table.DefaultTableModel.justifyRows(Unknown Source)
at javax.swing.table.DefaultTableModel.setDataVector(Unknown Source)
at javax.swing.table.DefaultTableModel.<init>(Unknown Source)
at JTableTest.rsToTableModel(JTableTest.java:80)
at JTableTest.connectDB(JTableTest.java:51)
at JTableTest.main(JTableTest.java:22)
我的第一个问题是我正在做向量吗?我不确定它是否应该将所有内容添加到行向量中,只是用逗号分隔的一个巨大的条目。我接近这个吗?我觉得我错过了什么..我假设我得到这个错误,因为该对象有5列包括整数和字符串,但不知道从哪里去。我所知道的是Jtable接受(向量,向量)或(object [] [],object()。我第一次使用mysql和jtables时感到很困惑。
答案 0 :(得分:1)
row = new Vector();
表示单行,而不是2D行集
你必须创建2D数组,例如Vector<Vector<Object>>() data = new Vector<Vector<Object>>();
,然后添加new row = new Vector<Object>()
;在Vector<Vector<Object>>();
while (rs.next()) {
更改返回new DefaultTableModel(row, columnNames);
以返回新的DefaultTableModel(data, columnNames);
覆盖getColumnClass
DefaultTableModel
不要重新发明轮子,搜索ResultSetTableModel
,TableFromDatabase
答案 1 :(得分:1)
根据提到的方法定义here, DefaultTableModel 构造函数的第一个参数应该是Vector of Vector。
在你的while循环中声明另一个Vector变量
while (rs.next()) {
java.util.Vector<Object> rowData = new java.util.Vector<Object>();
for (int i = 1; i < numberOfColumns; i++) {
rowData.addElement(rs.getObject(i));
}
// Here add that row data to the row vector
row.addElement(rowData);
}