使用 DriverManager 在 WAMP 上将 Java 连接到 MySQL

Connect Java to MySQL on WAMP using DriverManager

我正在尝试在与计算机 运行 相同的设备上连接到 WAMP 服务器上的数据库。下面是 zetcode 教程中的代码。除了 SQL 登录详细信息外,我几乎完全复制了它。我收到一个错误,它显示在代码下方。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.sun.corba.se.impl.util.Version;

public class TestDb {

public static void main(String[] args) {
    Connection con = null;
    Statement st = null;
    ResultSet rs = null;
    String url = "jdbc:mysql://localhost:3306/mltest";
    String user = "mlcomponents";
    String password = "color12";
    try {
        con = DriverManager.getConnection(url, user, password);
        st = con.createStatement();
        rs = st.executeQuery("SELECT VERSION()");

        if (rs.next()) {
            System.out.println(rs.getString(1));
        }

    } catch (SQLException ex) {
        Logger lgr = Logger.getLogger(Version.class.getName());
        lgr.log(Level.SEVERE, ex.getMessage(), ex);

    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
            if (con != null) {
                con.close();
            }

        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(Version.class.getName());
            lgr.log(Level.WARNING, ex.getMessage(), ex);
        }
    }
 }
}

我收到的错误消息:

May 25, 2016 3:51:28 PM TestDb main
SEVERE: No suitable driver found for jdbc:mysql://localhost:3306/mltest
java.sql.SQLException: No suitable driver found for   jdbc:mysql://localhost:3306/mltest
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at TestDb.main(TestDb.java:21)

我之前遇到过同样的问题,先尝试运行这个:

Class.forName("com.mysql.jdbc.Driver");

这将使驱动程序自行注册。

查看有关驱动器管理器的更多信息,MySQL Connector

来自上一个 link:

当您在应用程序服务器外部使用 JDBC 时,DriverManager class 会管理连接的建立。 向 DriverManager 指定 JDBC 个驱动程序尝试建立连接。最简单的方法是在实现 java.sql.Driver 接口的 class 上使用 Class.forName()。

编辑:我正在添加一个名为 MySQLConnector 的 java class,它可以根据您的第二个连接到 mysql(在本地主机中)题。看看我是如何导入 java.sql.DriverManager

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class MySQLConnector {
    //JDBC driver name and database URL
    private String JDBC_DRIVER;  
    private String DB_URL;
    //Database credentials
    private String USER;
    private String PASS;
    private Connection conn;

    public MySQLConnector(){
        JDBC_DRIVER = "com.mysql.jdbc.Driver";
        DB_URL = "jdbc:mysql://localhost/db_name?useUnicode=yes&characterEncoding=UTF-8";
        USER = "root";
        PASS = "123";
        conn = null;
    }
    public void openConnection(){
        try{
            //Register JDBC driver
            Class.forName(JDBC_DRIVER);         
            //Open a connection
            System.out.print("Connecting to a selected database... ");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            System.out.println("Success!");     
        }catch(Exception e){
            //Handle errors for JDBC
            e.printStackTrace();
        }
    }
    public void closeConnection(){
        try{
            if(conn!=null)
            conn.close();
        }catch(SQLException se){
            se.printStackTrace();
        }
        System.out.println("Connection closed");
    }
    public Connection getConnection(){
        return conn;
    }
}

首先在您的电脑上启动 Wamp,您不需要另一个 class 来建立连接,使用此代码并提供您的 wamp 登录的用户名和密码,此代码仅用于建立连接,自己添加以上功能

public class Jdbcdemo {

    public static void main(String[] args) {
       try
       {
           //loading the jdbc driver
            Class.forName("com.mysql.jdbc.Driver").newInstance();
           //get a connection to database
           Connection myConn=DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctry","your username","your password");
           //create a statement
           Statement stmt=myConn.createStatement();
           //execute sql query
           ResultSet rs=stmt.executeQuery("select * from employee");
           //process the result
           while(rs.next())
           {
               System.out.println(rs.getString("name")+" = "+rs.getString(1));
           }          
       }
       catch(SQLException e)
       {
           System.out.println(e);   
       }
       catch(Exception e)
       {
           System.out.println(e);
       }
    }

}