Java MySQL连接不起作用:找不到合适的驱动程序

huangapple go评论85阅读模式
英文:

Java MySQL connection not working: No suitable driver found

问题

public static void main(String args[]) {
    try {

        Connection myConn = DriverManager.getConnection(
            "jdbc:mysql://localhost/a3_eindopdracht_2", "", "");
        Statement myStm = myConn.createStatement();
        ResultSet myRs = myStm.executeQuery("SELECT * FROM namen");
        while (myRs.next()) {
            System.out.println(myRs.getString("voornaam") + " " + myRs.getString("achternaam"));
        }
    } catch (Exception exc) {
        exc.printStackTrace();
    }
}
英文:

So I am trying to make a connection with JDBC using XAMPP, but it doesn't work, What am I doing wrong here?

public static void main(String args[]) {
		try {

			Connection myConn = DriverManager.getConnection(
					"http://localhost/phpmyadmin/sql.php?db=a3_eindopdracht_2&table=namen&pos=0", "", "");
			Statement myStm = myConn.createStatement();
			ResultSet myRs = myStm.executeQuery("SELECT * FROM namen");
			while (myRs.next()) {
				System.out.println(myRs.getString("voornaam") + " " + myRs.getString("achternaam"));
			}
		} catch (Exception exc) {
			exc.printStackTrace();
		}

</details>


# 答案1
**得分**: 1

首先,你找不到 Driver。你必须通过调用 Drive 类来加载它们,就像这样:

```java
try {
    Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
    // 无法找到 MySQL 的驱动程序
}

然后,你正在尝试使用 HTTP 协议连接到你的数据库。但是,数据库有它们自己的协议(默认情况下使用端口 3306),所以你必须使用类似这样的地址:

jdbc:mysql://myserver.com/schema

最后:不要忘记在 getConnection 方法的最后两个字段中添加用户名和密码。

英文:

Firstly, you don't find Driver. You have to load them, by calling the Drive class like that :

try {
	Class.forName(&quot;com.mysql.jdbc.Driver&quot;);
} catch (ClassNotFoundException e) {
	// Cannot find driver for MySQL
}    

Then, you are trying to connect to your databse with HTTP protocol. But, DB have they own (with port 3306 by default), so you have to use address like that:

jdbc:mysql://myserver.com/schema

Finally: don't forget to add username and password on last 2 fields of getConnection method

huangapple
  • 本文由 发表于 2020年9月11日 15:25:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/63842554.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定