Java连接到mySQL

时间:2018-05-30 22:58:14

标签: java mysql jdbc

你好我在我的mac上运行了mysql,我正在尝试编写一个java脚本来连接它:

private static final String USERNAME = "root";
private static final String PASSWORD = "password";
private static final String CONN_STRING = "jdbc:mysql://local:3306/test";

public static void main(String[] args) {
    Connection conn = null;

    try {
        conn = DriverManager.getConnection(CONN_STRING,USERNAME,PASSWORD);
        System.out.println("Connected");
    }catch (SQLException e){
    System.err.println(e);
    }
}

然而我一直收到此错误消息

java.sql.SQLException:没有为jdbc找到合适的驱动程序:mysql:// local:3306 / test

我做错了什么?

2 个答案:

答案 0 :(得分:1)

首先,您必须将Mysql jdbc驱动程序添加为外部库。您可以从here找到jar文件。这个link指导如何在netbeans中添加库。其他问题是import os import logging import pybrake from django.test import SimpleTestCase logger = logging.getLogger(__name__) class AirbrakeTest(SimpleTestCase): def test_1(self): notifier = pybrake.Notifier( project_id=os.getenv('AIRBRAKE_PROJECT_ID'), project_key=os.getenv('AIRBRAKE_PROJECT_KEY'), environment='production', root_directory=os.path.dirname(os.getcwd())) try: raise ValueError("Hello") except Exception as err: notifier.notify(err) def test_2(self): logger.error("Foobar") 必须是pybrake.Notifier

local

答案 1 :(得分:0)

在类路径中使用驱动程序后,需要在获取连接之前添加以下行,并在CONN_STRING中将本地更改为localhost:

DriverManager.registerDriver(new com.mysql.jdbc.Driver());

这样的事情:

try {
        DriverManager.registerDriver(new com.mysql.jdbc.Driver ());
        conn = DriverManager.getConnection(CONN_STRING,USERNAME,PASSWORD);
        System.out.println("Connected");
    }catch (SQLException e){
    System.err.println(e);
    }