为什么应用程序找不到JDBC驱动程序?

时间:2016-06-30 10:32:21

标签: java database jdbc jtds

为什么应用程序找不到jdbc驱动程序?

//  TODO Auto-generated method stub
Connection connection = null;
try {
    // String driverName = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
    String driverName = "sun.jdbc.odbc.JdbcOdbcDriver";
    String serverName = "serverName";
    String databaseName = "databaseName";
    String portNumber = "portNumber";
    String myDatabase = serverName + ":" + portNumber;
    String domainName = "domain name";
    String url = "jdbc:jtds:sqlserver://" + myDatabase + ";Database=" + databaseName + ";domain=" + domainName; // a JDBC url
    String username = "username";
    String password = "password";

    // Load the JDBC driver
    Class.forName(driverName);

    // Create a connection to the database
    connection = DriverManager.getConnection(url, username, password);


    // Execute a query
    Statement stmt = connection.createStatement();
    String sql;
    sql="SELECT CODFISC, SURNAME FROM tbPersonale order by SURNAME;";
    ResultSet rs = stmt.executeQuery(sql);

    // Estrazione Dati  
    while(rs.next() ) {

        // Legge i valori
        String CODFISC = rs.getString("CODFISC"); //CODFISC is the fiscal code
        String SURNAMENAME = rs.getString("SURNAME");

        // Visualizza i dati
        System.out.print("Codice Fiscale: " + CODFISC );
        System.out.println("SURNAME and NAME: " + SURNAMENAME );

    }

} catch (ClassNotFoundException e) {
    System.out.println("Could not find the database driver"); // here is where i always end up :(
} catch (SQLException e) {
    System.out.println("Could not connect to the database");
}   

1 个答案:

答案 0 :(得分:1)

由于您显然希望使用JTDS驱动程序连接到SQL Server,请确保

  • JTDS jar在类路径中
  • 并使用正确的驱动程序类名称。

现在您正在使用ODBC Bridge驱动程序(已在Java 8中删除),而不是您想要的

String driverName = "net.sourceforge.jtds.jdbc.Driver";