当前位置: 技术问答>java相关
在线等待:怎么不能对数据库操作呀??
来源: 互联网 发布时间:2015-10-06
本文导语: 我下面的程序怎么不能访问数据库呀: //OpenDB.java import java.sql.*; public class OpenDB { String sDBDriver = "sun.jdbc.odbc.JdbcOdbcDriver"; String sConn = "jdbc:odbc:cs"; Connection conn = null; ResultSet rs = null; public OpenDB() { try { ...
我下面的程序怎么不能访问数据库呀:
//OpenDB.java
import java.sql.*;
public class OpenDB {
String sDBDriver = "sun.jdbc.odbc.JdbcOdbcDriver";
String sConn = "jdbc:odbc:cs";
Connection conn = null;
ResultSet rs = null;
public OpenDB() {
try {
Class.forName(sDBDriver);
}
catch (java.lang.ClassNotFoundException e) {
System.out.println("OpenDB():"+e.getMessage());
}
}
public ResultSet executeQuery(String sql) {
try {
conn = DriverManager.getConnection(sConn);
Statement stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
}
catch (java.sql.SQLException e) {
System.out.println("OpenDB.executeQuery:"+e.getMessage());
}
return rs;
}
public static void main(String[] args) {
OpenDB op=new OpenDB();
ResultSet RS=op.executeQuery("select * from person");
//person为odbc数据源,连结的是access数据库
while(RS.next()){
System.out.println("name");
}
RS.close();
}
}
//OpenDB.java
import java.sql.*;
public class OpenDB {
String sDBDriver = "sun.jdbc.odbc.JdbcOdbcDriver";
String sConn = "jdbc:odbc:cs";
Connection conn = null;
ResultSet rs = null;
public OpenDB() {
try {
Class.forName(sDBDriver);
}
catch (java.lang.ClassNotFoundException e) {
System.out.println("OpenDB():"+e.getMessage());
}
}
public ResultSet executeQuery(String sql) {
try {
conn = DriverManager.getConnection(sConn);
Statement stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
}
catch (java.sql.SQLException e) {
System.out.println("OpenDB.executeQuery:"+e.getMessage());
}
return rs;
}
public static void main(String[] args) {
OpenDB op=new OpenDB();
ResultSet RS=op.executeQuery("select * from person");
//person为odbc数据源,连结的是access数据库
while(RS.next()){
System.out.println("name");
}
RS.close();
}
}
|
因为这两句话有可能异常
java里认为,如果可能有异常,你就必须捕捉或者throw
改成
try{
ResultSet RS=op.executeQuery("select * from person");
//person为odbc数据源,连结的是access数据库
while(RS.next()){
System.out.println("name");
}
RS.close();
}
catch(Exception ex){
}
java里认为,如果可能有异常,你就必须捕捉或者throw
改成
try{
ResultSet RS=op.executeQuery("select * from person");
//person为odbc数据源,连结的是access数据库
while(RS.next()){
System.out.println("name");
}
RS.close();
}
catch(Exception ex){
}
|
建ODBC时选择DSN(系统)