关于java不用odbc设置数据源连接access的编程问题
本人是菜鸟,刚刚学JAVA,求老手 修改指导!!!!
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.DriverManager;
public class MyExample {
public static void main(String []args) throws Exception {
String url="jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=book.mdb";
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
String command = "select * from book where bno='1'";
ResultSet rs = stmt.executeQuery(command);
String x1=rs.getString(1);String x2= rs.getString(2);String x3=rs.getString(3);
String x4= rs.getString(4);float x5=rs.getFloat(5);String x6=rs.getString(6);
while(rs.next()) {
System.out.print(" " + x1 + " ");
System.out.print(" " + x2 + " ");
System.out.print(" " + x3 + " ");
System.out.print(" " + x4 + " ");
System.out.print(" " + x5 + " ");
System.out.print(" " + x6 + " ");conn.close();
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
异常:
java.sql.SQLException: [Microsoft][ODBC 驱动程序管理器] 无效的游标状态
at sun.jdbc.odbc.JdbcOdbc.create
SQLException(JdbcOdbc.java:6957)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7114)
at sun.jdbc.odbc.JdbcOdbc.SQLGetDataString(JdbcOdbc.java:3907)
at sun.jdbc.odbc.JdbcOdbcResultSet.getDataString(JdbcOdbcResultSet.java:5698)
at sun.jdbc.odbc.JdbcOdbcResultSet.getString(JdbcOdbcResultSet.java:354)
at MyExample.main(MyExample.java:18)
------解决方案--------------------
Java code
String x1=rs.getString(1);String x2= rs.getString(2);String x3=rs.getString(3);
String x4= rs.getString(4);float x5=rs.getFloat(5);String x6=rs.getString(6);
while(rs.next()) {
System.out.print(" " + x1 + " ");
System.out.print(" " + x2 + " ");
System.out.print(" " + x3 + " ");
System.out.print(" " + x4 + " ");
System.out.print(" " + x5 + " ");
System.out.print(" " + x6 + " ");conn.close();
}
}
catch(Exception e) {
e.printStackTrace();
}
------解决方案--------------------
conn.close();
这句话不能放在while循环里面。
可以放在整个while块后面。