求教数据库连接问题
import java.sql.*;import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class DisplayQueryResults extends JFrame{
private Connection connection;
private ResultSet resultSet;
private Statement statement;
private ResultSetMetaData rsMetaData;
private JTable table;
private JButton submitQuery;
private JTextArea inputQuery;
public DisplayQueryResults(){
super("Enter Query Click Submit to see Results.");
String url="jdbc:odbc:Book";
String username="zhang";
String password="111";
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection=DriverManager.getConnection(url,username,password);
}catch(ClassNotFoundException cnfex){
System.err.println("Failed to load JDBC\\ODBC driver");
cnfex.printStackTrace();
System.exit(1);
}catch(SQLException sqlex){
System.err.print("Unable to cpnnect");
sqlex.printStackTrace();
System.exit(1);
}
inputQuery=new JTextArea("SELECT * FROM Author",4,30);
submitQuery=new JButton("Submit Query");
submitQuery.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(e.getSource()==submitQuery)
getTable();
}
});
JPanel topPanel=new JPanel();
topPanel.setLayout(new BorderLayout());
topPanel.add(new JScrollPane(inputQuery),BorderLayout.CENTER);
topPanel.add(submitQuery,BorderLayout.SOUTH);
table=new JTable(4,4);
Container c=getContentPane();
c.setLayout(new BorderLayout());
c.add(topPanel,BorderLayout.NORTH);
c.add(table,BorderLayout.CENTER);
getTable();
setSize(500,500);
setVisible(true);
}
private void getTable(){
try{
String query=inputQuery.getText();
statement=connection.createStatement();
resultSet=statement.executeQuery(query);
displayResultSet(resultSet);
}catch(SQLException sqlex){
sqlex.printStackTrace();
}
}
private void displayResultSet(ResultSet rs)
throws SQLException
{
boolean moreRecords=rs.next();
if(!moreRecords){
JOptionPane.showMessageDialog(this,"ResultSet contained no records");
setTitle("No record to display");
return;
}
Vector columnHeads=new Vector();
Vector rows=new Vector();
try{
ResultSetMetaData rsmd=rs.getMetaData();
for(int i=0;i<rsmd.getColumnCount();i++)
columnHeads.addElement(rsmd.getColumnClassName(i));
do{
rows.addElement(getNextRow(rs,rsmd));
}while(rs.next());
table=new JTable(rows,columnHeads);
JScrollPane scroll=new JScrollPane(table);
Container c=getContentPane();
c.remove(1);
c.add(scroll,BorderLayout.CENTER);
c.validate();
}catch(SQLException sqlex){
sqlex.printStackTrace();
}
}
private Vector getNextRow(ResultSet rs,ResultSetMetaData rsmd)
throws SQLException{
Vector currentRow=new Vector();
for(int i=0;i<rsmd.getColumnCount();i++){
switch(rsmd.getColumnType(i)){
case Types.VARCHAR:
case Types.LONGVARCHAR:
currentRow.addElement(rs.getString(i));
break;
default:
System.out.println("Type was:"+rsmd.getColumnTypeName(i));
}
}
return currentRow;
}
public static void main(String[] args){
new DisplayQueryResults();
}
}
本人初学请大家帮忙指教一下这是什么问题,万分感激!!
[此贴子已经被作者于2007-3-23 13:08:51编辑过]