JAVA中的SELECT语句

Cry*_*den 9 java swing select sql-server-2005 jtable

    public void search() throws Exception{
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                String url = "jdbc:odbc:******";
                String user = "*****";
                String pass = "*****";
                Connection con =  DriverManager.getConnection(url, user, pass);
                Statement state = con.createStatement();
                ResultSet rs = state.executeQuery("");
                ResultSetMetaData rsmetadata = rs.getMetaData();
                int columns = rsmetadata.getColumnCount();
                DefaultTableModel dtm = new DefaultTableModel();
                Vector column_name = new Vector();
                Vector data_rows = new Vector();

                for (int i=1; i<columns;i++){
                    column_name.addElement(rsmetadata.getColumnName(i));
                }
                dtm.setColumnIdentifiers(column_name);

                while(rs.next()){
                    data_rows = new Vector();
                    for (int j=1; j<columns; j++){
                    data_rows.addElement(rs.getString(j));
                    }
                    dtm.addRow(data_rows);
                }
                tblPatient.setModel(dtm);
        }
Run Code Online (Sandbox Code Playgroud)

在我的ResultSet rs = state.executeQuery()我用这个SQL

                              "SELECT "
                            + "pIDNo AS 'Patient ID',"
                            + "pLName AS 'Last Name'," 
                            + "pFName AS 'First Name',"
                            + "pMI AS 'M.I.',"
                            + "pSex AS 'Sex',"
                            + "pStatus AS 'Status',"
                            + "pTelNo AS 'Contact No.',"
                            + "pDocID AS 'Doctor ID',"
                            + "pAddr AS 'St. No.',"
                            + "pStreet AS 'St. Name',"
                            + "pBarangay AS 'Barangay',"
                            + "pCity AS 'City',"
                            + " pProvince AS 'Province',"
                            + " pLNameKIN AS 'Last Name',"
                            + "pFNameKIN AS 'First Name',"
                            + "pMIKIN AS 'M.I.',"
                            + "pRelationKIN AS 'Relation',"
                            + "pTotalDue AS 'Total Due'"
                            + " FROM dbo.Patients"); 
Run Code Online (Sandbox Code Playgroud)

首先我运行这一行(pTotalDue没有达到jTable.)

在我第二次尝试显示它时,我这样做:

"SELECT pTotalDue AS 'Total Due' FROM dbo.Patients"
Run Code Online (Sandbox Code Playgroud)

现在我尝试了这个,我认为我的代码确实存在问题.BTW此栏有货币数据类型

为什么它没有显示给我JTable?谁能告诉我我的代码有什么问题?

(给出的答案中的问题)公共类QueryOnWorkerThread扩展了SwingWorker {private final JTable tableToUpdate;

  public QueryOnWorkerThread( JTable aTableToUpdate ) {
    tableToUpdate = aTableToUpdate;
  }

  @Override
  protected TableModel doInBackground() throws Exception {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String url = "jdbc:odbc:OJT_dsn";
    String user = "sa";
    String pass = "";
    Connection con =  DriverManager.getConnection( url, user, pass );
    Statement state = con.createStatement();
    ResultSet rs = state.executeQuery("");
    ResultSetMetaData rsmetadata = rs.getMetaData();
    int columns = rsmetadata.getColumnCount();
    DefaultTableModel dtm = new DefaultTableModel();
    Vector column_name = new Vector();
    Vector data_rows;

    //note the <= check iso the < check (as the count starts at index 1)
    for (int i=1; i<=columns;i++){
      column_name.addElement(rsmetadata.getColumnName(i));
    }
    dtm.setColumnIdentifiers(column_name);

    while(rs.next()){
      data_rows = new Vector();
      //note the <= check iso the < check (as the count starts at index 1)
      for (int j=1; j<=columns; j++){
        data_rows.addElement(rs.getString(j));
      }
      dtm.addRow(data_rows);
    }
    return dtm;
  }


        `@Override <<<<<<<<<<<<<<<<<<<<< I have a problem here it says : done() in javaapplication25.SearchPatient.QueryWorkerThread cannot override done() in javax.swing.SwingWorker overriden method does not throw java.lang.Exception , what does it mean sir?` 
  protected void done() throws Exception{
    //this method runs on the EDT, so it is safe to update our table here
    try {
      tableToUpdate.setModel( get() );
    } catch ( InterruptedException e ) {
      throw new RuntimeException( e );
    } catch ( ExecutionException e ) {
      throw new RuntimeException( e );
    }
  }
Run Code Online (Sandbox Code Playgroud)

Nid*_*nan 8

试试这个

DefaultTableModel dtm=(DefaultTableModel)table.getModel();
for (int i = dtm.getRowCount() - 1; i > -1; i--) {
dtm.removeRow(i);
}

Connection con =  DriverManager.getConnection(url, user, pass);
Statement state = con.createStatement();
ResultSet rs = state.executeQuery("Your SQL Query");

while(rs.next())
{
String str1=rs.getString(1);
String str2=rs.getString(2);
String str3=rs.getString(3);
String str4=rs.getString(4);
String str5=rs.getString(5);
:
:
:
dtm.addRow(new Object[]{str1,str2,str3,str4,str5});
}
Run Code Online (Sandbox Code Playgroud)


Joa*_*oan 6

在循环中,退出条件是

j<columns 
Run Code Online (Sandbox Code Playgroud)

这意味着最后一列永远不会被恢复.尝试这个insted:

for (int j=1; j<=columns; j++)
Run Code Online (Sandbox Code Playgroud)


Rob*_*bin 5

你的最后一列没有出现的事实可能与你的循环语句有关,正如@Joan已经指出的那样.

但是,此代码存在更多问题.您应该只更新Event Dispatch Thread上的Swing组件,并且在该Thread上您不应该执行长时间运行的操作.简而言之,混合SQL查询和更新JTable不应该发生在同一个线程上.有关详细信息,请参阅Swutch中Concurrency指南.

使用a SwingWorker可以解决这个问题:

public class QueryOnWorkerThread extends SwingWorker<TableModel, Void>{
  private final JTable tableToUpdate;

  public QueryOnWorkerThread( JTable aTableToUpdate ) {
    tableToUpdate = aTableToUpdate;
  }

  @Override
  protected TableModel doInBackground() throws Exception {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String url = "jdbc:odbc:******";
    String user = "*****";
    String pass = "*****";
    Connection con =  DriverManager.getConnection( url, user, pass );
    Statement state = con.createStatement();
    ResultSet rs = state.executeQuery("");
    ResultSetMetaData rsmetadata = rs.getMetaData();
    int columns = rsmetadata.getColumnCount();
    DefaultTableModel dtm = new DefaultTableModel();
    Vector column_name = new Vector();
    Vector data_rows;

    //note the <= check iso the < check (as the count starts at index 1)
    for (int i=1; i<=columns;i++){
      column_name.addElement(rsmetadata.getColumnName(i));
    }
    dtm.setColumnIdentifiers(column_name);

    while(rs.next()){
      data_rows = new Vector();
      //note the <= check iso the < check (as the count starts at index 1)
      for (int j=1; j<=columns; j++){
        data_rows.addElement(rs.getString(j));
      }
      dtm.addRow(data_rows);
    }
    return dtm;
  }

  @Override
  protected void done() {
    //this method runs on the EDT, so it is safe to update our table here
    try {
      tableToUpdate.setModel( get() );
    } catch ( InterruptedException e ) {
      throw new RuntimeException( e );
    } catch ( ExecutionException e ) {
      throw new RuntimeException( e );
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

SwingWorker可以通过调用启动

QueryOnWorkerThread worker = new QueryOnWorkerThread( tblPatient );
worker.execute();
Run Code Online (Sandbox Code Playgroud)

请注意我是如何更改代码中的循环的