2 sidemengyi sidemengyi 于 2014.10.29 15:21 提问

请问大神这个程序问题出在哪里啊

这样是没问题的
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestJDBC {
public static void main(String[] args) throws ClassNotFoundException,SQLException {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://localhost:1433;DatabaseName=HYGJ_0922";
Connection conn = DriverManager.getConnection(url, "sa", "123");z
Statement smst = conn.createStatement();
ResultSet rs = smst.executeQuery("select * from TBL_COURSE");
while (rs.next()) {
System.out.print(rs.getString("COU_NO") + ":");
System.out.println(rs.getString("COU_NAME"));
}
rs.close();
smst.close();
conn.close();
}
}
但是加上TRY语句块的话 就会报错
java.sql.SQLException: No suitable driver found for jdbc:sqlserver:localhost:1433;DatabaseName=HYGJ_0922
代码如下,谢谢大神
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestJDBC2 {
public static void main(String[] args) {
ResultSet rs = null;
Statement stmt = null;
Connection conn = null;
try {

        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        String url = "jdbc:sqlserver:localhost:1433;DatabaseName=HYGJ_0922";
        conn = DriverManager.getConnection(url, "sa", "123");
        stmt = conn.createStatement();
        rs = stmt.executeQuery("select * from TBL_COURSE");

        while (rs.next()) {
            System.out.println("TRE_NAME");
        }

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (rs != null) {
                rs.close();
                rs = null;
            }
            if (stmt != null) {
                stmt.close();
                stmt = null;
            }
            if (conn != null) {
                conn.close();
                conn = null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

}

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!