使用jdbc驱动程序连接到MySQL

时间:2016-05-12 04:35:52

标签: java mysql jdbc

我创建了一个名为BD的类,其中我尝试与名为bono

的数据库建立连接
public class BD {
String url,login,password,driver;
Connection conexion=null;

public BD(){
    driver = "com.mysql.jdbc.Driver";
    url = new String("jdbc:mysql://localhost:8000/bono");
    login = new String("root");
    password = new String("mypassword");
    try {
        Class.forName(driver);
        conexion = DriverManager.getConnection(url, login, password);
        System.out.println("Conexi�n con Base de datos Ok....");
    } catch (ClassNotFoundException e) { // 
        System.out.println("error 1");
    } catch (SQLException e) {
        System.out.println("error 2");
    }
}

但是当我执行它时,它只会停留在以下行中:

conexion = DriverManager.getConnection(url, login, password);

它不会发送任何错误,也不会建立连接。我该怎么办?

2 个答案:

答案 0 :(得分:2)

尝试将您的端口更改为3306.

public class BD {
String url,login,password,driver;
Connection conexion=null;

public BD(){
    driver = "com.mysql.jdbc.Driver";
    url = new String("jdbc:mysql://localhost:3306/bono");
    login = new String("root");
    password = new String("mypassword");
    try {
        Class.forName(driver);
        conexion = DriverManager.getConnection(url, login, password);
        System.out.println("Conexi�n con Base de datos Ok....");
    } catch (ClassNotFoundException e) { // 
        System.out.println("error 1");
        e.printStackTrace();
    } catch (SQLException e) {
        System.out.println("error 2");
        e.printStackTrace();
    }
}

希望它有所帮助。

注意:确保MySQL正在运行。尝试类似的东西: 来自您的控制台的mysqladmin -u root -p status,不应显示任何错误

答案 1 :(得分:2)

我认为您的端口可能不正确:希望至少看到一些异常

尝试此代码
@Override
public int insertNewApplication(StudenDetails sd)
{
    String sql = "INSERT INTO student_details"
            + "(applicant_name, applsex, "
            + "designation, date_of_superannuation, "
            + "ou_code, residential_address, "
            + "phone_no, mobile_no,email_id,token_user_id,token_password, "
            + "staff_status,office_type_code) VALUES (?, ?, ?,to(?,'DD/MM/YYYY'), ?, ?, ?, ?, ?, ?, ?,?,?)";

    return jdbcTemplate.update(sql, new Object[] {
            tpd.getApplicant_name(), tpd.getApplsex(),tpd.getDesignation(),tpd.getDate_of_superannuation(),tpd.getOu_code(),tpd.getResidential_address(),tpd.getPhone_no(),tpd.getMobile_no(),
            tpd.getEmail_id(),tpd.getToken_user_id(),tpd.getToken_password(),tpd.getStaff_status(),tpd.getOffice_type_code()
            });

}