javaandroiddatabasesqljdbc

ClassNotFoundException Class.forName() in android


try {
    String url = "jdbc:sqlserver://Aman\\SQL12;databaseName=P2C_Android";
    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    conn = DriverManager.getConnection(url, "sa", "aman");
    String sql =
        "select * from UserTable " +
        "where username='" + username.getText().toString() +
        "' and password='" + password.getText().toString() + "'";
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(sql);
    if (rs != null && rs.next())
        Toast.makeText(getApplicationContext(), "Redirecting...",
            Toast.LENGTH_SHORT).show();
    else {
        Toast.makeText(getApplicationContext(), "Wrong Credentials",
            Toast.LENGTH_SHORT).show();
        attempts.setBackgroundColor(Color.RED); 
        counter-- ;
        attempts.setText(Integer.toString(counter));
        if(counter == 0)
            login.setEnabled(false);
    }

}
catch (Exception ex) {
    Toast.makeText(getApplicationContext(),
        ex.getMessage(), Toast.LENGTH_SHORT).show();
}

It says class not found even when I can see that the class is present in sqljdbc.jar that I have added.
I am trying to access a database from an android application.


Solution

  • Make sure if you have only one version of JAR.

    For ex-

    You may have both sqljdbc.jar or sqljdbc4.jar in the classpath.