在eclipse中使用JDBC连接到MySQL

时间:2010-04-17 14:09:57

标签: mysql eclipse jdbc

所以我想创建一个安装在我的电脑上的MySQL服务器的JDBC连接,这里是步骤, 我使用用户名和密码“root”安装了MySQL,下载了mysql-connector-java,然后我将JAR“mysql-connector-java-5.1.12-bin”应用到了“C:\ Sun \ SDK \ jdk \ jre” \ lib \ ext“,然后我在eclipse中的项目中将其添加为外部JAR,现在在我的课程中我有这段代码:

public void initialiseDatabase()
        {
            try { 
            // Load the Driver class. 
            Class.forName("com.mysql.jdbc.Driver"); 

            //Create the connection using the static getConnection method 
            databaseConnection = DriverManager.getConnection (databaseUrl+databaseName, 
                    dbUserName, dbPassword);
            sqlStatement = databaseConnection.createStatement();
            }
            catch (SQLException e) {e.printStackTrace();} 
            catch (Exception e) {e.printStackTrace();}
        }

(这将是psuedocode,因为我正在读取属性文件,并且不希望那个帮助我阅读main中的长行代码以找出所有变量), 其中databaseUrl =“127.0.0.1” dbUserName =“root”  dbPassword =“root” databaseName =“MySQL”//这个我不确定,我需要创建它还是设置不正常?

现在MySQL服务器启动并运行,但是当我调用方法initialiseDatabase时,抛出以下异常: “java.sql.SQLException:找不到适合rootroot的驱动程序     at java.sql.DriverManager.getConnection(Unknown Source)     at java.sql.DriverManager.getConnection(Unknown Source)     在Proxy $ JDBCConnection.initialiseDatabase(Proxy.java:721)“

当第721行是: sqlStatement = databaseConnection.createStatement();

我哪里出错?

感谢

1 个答案:

答案 0 :(得分:3)

您的数据库网址应如下所示:

jdbc:mysql://host:port/database

例如,如果您使用localhost,默认端口和名为cachedb的数据库,您的网址将为:

jdbc:mysql://localhost/cachedb