1

我是 Java 的新手。在这里,我试图在我的代码中连接到 mysql 数据库:包服务;

package Services;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class LoginService {
     private static final String USERNAME="root";
     private static final String PASSWORD="";
     private static final String CONNECTION_STRING="jdbc:mysql://localhost/testdb";

    public void  Authenticate(String uname,String password){

        Connection connection=null;
        Statement statement=null;
        ResultSet result =null;
        try{
            //Class.forName("com.mysql.jdbc.Driver").newInstance();//if java 6 or higher there is no need to load cass      
        connection =(Connection)DriverManager.getConnection(CONNECTION_STRING,USERNAME,PASSWORD);
        System.out.println("Connection to the database is established ");
        }catch(SQLException e){
            System.out.println("Can't connect to db:" +e );

        }   

    }


}

这最终会出现如下错误:

Can't connect to db:java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/testdb

我已经添加了 jar 文件,并通过右键单击它添加了相同的构建路径;我的代码有什么问题。

4

1 回答 1

0

您必须下载 JDBC 驱动程序......之后......将其添加到您的库中......您可以阅读此内容!明白之后真的很简单!链接在这里!http://dev.mysql.com/doc/connector-j/en/connector-j-usagenotes-connect-drivermanager.html

和这个!http://www.mkyong.com/jdbc/how-to-connect-to-mysql-with-jdbc-driver-java/

祝你好运!

于 2013-08-02T09:49:58.910 回答