【问题标题】:In a database connection, what Class.forName does?在数据库连接中,Class.forName 做什么?
【发布时间】:2019-05-09 08:37:38
【问题描述】:

我在教程中看到使用“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;
    }
}

【问题讨论】:

  • 它定义了需要使用哪个Driver类进行连接。
  • @mohammadReza 抱歉,我是 Java 编程新手,所以我可能听起来很愚蠢,但是 Driver 类有什么用?
  • 驱动类使java应用程序能够与数据库交互。就像您提供的 class=net.sourceforge.jtds.jdbc.Driver
  • 还有一个问题。 net.sourceforge.jtds.jdbc.Driver 是通用的还是我需要专门为我的服务器使用它?
  • 驱动类取决于你的数据库。

标签: java android sql-server


【解决方案1】:

看不到错误信息,可能是格式不正确。通常我会写:

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

【讨论】:

  • 对不起,我还以为搞错了。
猜你喜欢
  • 2013-12-03
  • 2011-12-24
  • 2011-10-08
  • 2014-04-25
  • 2016-03-24
  • 2011-06-06
  • 2013-02-08
  • 1970-01-01
相关资源
最近更新 更多