帮忙看看,数据库可以创建表,却不能查询,为什么?

joy8223 2003-09-16 10:24:11
import java.sql.*;
import java.util.*;
public class Books{
String error;
Connection con;
public Books(){}
public void connect() throws ClassNotFoundException,SQLException,Exception{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
con=DriverManager.getConnection("jdbc:odbc:test","sa", "linchun");
}catch(ClassNotFoundException cnfe){
error="ClassNotFoundException:Could not locate DB driver.";
throw new ClassNotFoundException(error);
}catch(SQLException cnfe){
error="SQLException:Could not connect to database.";
throw new SQLException(error);
}catch(Exception e){
error="Exception:An unknown error occurred while connecting to database.";
throw new Exception(error);
}
}
public void disconnect() throws SQLException{
try{
if (con!=null){
con.close();
}
}catch(SQLException sqle){
error="SQLException:Unable to close the database connection.";
throw new SQLException(error);
}
}
public ResultSet viewBooks() throws SQLException,Exception{
ResultSet rs=null;
try{
String queryString=("SELECT * FROM Authors;");
Statement stmt=con.createStatement();
rs=stmt.executeQuery("select * from Authors");

// String upd="CREATE TABLE Authors(Author_ID INTEGER NOT NULL PRIMARY KEY,Author_Name CHAR(50));";
// String upd="insert into Authors values(2,'name')";
// stmt.executeUpdate(upd);
// System.out.println("Table - Authors created");
System.out.println(rs.getString("Author_Name"));
}catch(SQLException sqle){
error="SQLException:Could not execute the query.";
throw new SQLException(error);
}catch(Exception e){
error="An exception occured while retrieving books.";
throw new Exception(error);
}
return rs;
}
public static void main(String [] args) throws Exception{
Books book=new Books();
book.connect();
System.out.println("connected");
ResultSet rs=null;
rs=book.viewBooks();
book.disconnect();
System.out.println("disconnected");
}
}



数据库可以创建表,却不能查询,老是出现错误:
connected
java.sql.SQLException: SQLException:Could not execute the query.
at Books.viewBooks(Books.java:47)
at Books.main(Books.java:59)
Exception in thread "main"
但创建表和插入纪录就没有错误,是不是我哪里错了?
...全文
31 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
phoenix7789 2003-09-16
  • 打赏
  • 举报
回复
记录集指针没有下移,要先执行rs.next();,之后才能读取记录。因为记录集产生之后,指针在第一条记录之前的零位置上。
具体写法见楼上的。

--------------------------
让生命时刻充满着激情!
sgdb 2003-09-16
  • 打赏
  • 举报
回复
rs=stmt.executeQuery("select * from Authors");
if (rs.next()){
System.out.println(rs.getString("Author_Name"));
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧