gpt4 book ai didi

java - 添加数据库中不存在的额外列

转载 作者:行者123 更新时间:2023-12-01 14:45:56 24 4
gpt4 key购买 nike

下面是我从数据库创建表的代码。我想在末尾添加一个复选框列,该复选框列不会出现在数据库中。它只是前端的一部分。您能帮忙吗?

尽管选择了一行,我的 getRow() 方法仍然返回 -1,有什么建议吗?

  package Default;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.*;
import java.sql.*;

/**
* This class create JTable from Database table.
* User program needs to specify database connection and corresponding a table name.
*
*/

public class DBTable{
//private String table;

DefaultTableModel dm=new DefaultTableModel();
JTable t1=new JTable();
Object row[];
String c[];
int cols;
PreparedStatement pst;
ResultSet rs ;

public DBTable(Connection conn){
conn=Login.con;
}

/**
* This method return JTable object created from Database table having selected data and structur * as in original table into database.
* @param table Name of the database table to be coverted to JTable
* @param query Select query to specify selected columns and data to extracted from database table
* @return JTable object that consist of selected data and structure of Database table
* @throws java.lang.Exception Original object is deferent, e.i either SQLException or NullPointerException
*/

public JTable getTable(String table,String query)throws Exception{

JTable t1=new JTable();
DefaultTableModel dm=new DefaultTableModel();
Statement st= Login.con.createStatement();
ResultSet rs=st.executeQuery(query);
ResultSetMetaData rsmd=rs.getMetaData();
//Coding to get columns-
int cols=rsmd.getColumnCount();
String c[]=new String[cols];
for(int i=0;i<cols;i++){
c[i]=rsmd.getColumnName(i+1);
dm.addColumn(c[i]);
}



//get data from rows
Object row[]=new Object[cols];
while(rs.next()){
for(int i=0;i<cols;i++){
row[i]=rs.getString(i+1);
}
dm.addRow(row);
}
t1.setModel(dm);


return t1;
}


public int getRow(){

int row = t1.getSelectedRow();
JOptionPane.showMessageDialog(null, row);

return row;
}

public void deleteRow(String sql){

try {
String value = (String) t1.getValueAt(getRow(), 0);
JOptionPane.showMessageDialog(null, value);
pst = Login.con.prepareStatement(sql);
pst.setString(1, value);
((DefaultTableModel)t1.getModel()).removeRow(getRow());
pst.execute();
JOptionPane.showMessageDialog(null, "Deleted");


} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}
}
}

最佳答案

您正在使用 DefaultTableModel,因此在创建模型后您可以手动添加列:

model.addColumn("CheckBox Column");

关于java - 添加数据库中不存在的额外列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15436568/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com