在数据库连接中,Class.forName做什么?

时间:2019-05-09 08:37:38

标签: java android sql-server

我在教程中看到了“ Class.forName”的使用。请让我知道它的作用,以及此代码是否可以正常工作?

 public class Conexao {
    String ip = "ip";
    String class = "net.sourceforge.jtds.jdbc.Driver";
    String bd = "nomeBD";
    String username = "UserName";
    String password = "password";

    @SuppressLint("NewApi")
    public Connection CONN() {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Connection conn = null;
        String ConnURL;
        try {
            Class.forName(class);
            ConnURL = "jdbc:jtds:sqlserver://" + ip + ";" + "databaseName=" + bd + ";user=" + username + ";password=" + password + ";";
            conn = DriverManager.getConnection(ConnURL);
        } catch (SQLException se) {
            Log.e("ERROR", se.getMessage());
        } catch (Exception e) {
            Log.e("ERROR", e.getMessage());
        }
        return conn;
    }
}

1 个答案:

答案 0 :(得分:0)

看不到错误消息,它的格式可能不正确。通常我写:

String url = "jdbc:mysql://localhost:3306/samp_db";
...
DriverManager.getConnection(url, username, password);
....