日期:2014-05-20  浏览次数:20797 次

连接mysql数据库
public class MyDB{
    private Connection conn=null;
    private String jdbcUrl="jdbc:mysql://localhost:3360/manger";
    private String user="root";
    private String password="123456";
    public  Connection getConn(){
        try{
            Class.forName("com.mysql.jdbc.Driver");
            conn=DriverManager.getConnection(jdbcUrl, user,password);
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return conn;
    }
    public void closeConn(){
        try{
            conn.close();
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}
这是连接数据库的代码,
这是测试的:
import java.sql.*;

public class TestDB
{
    public static void main(String[] args) throws SQLException
    {
     MyDB my=new MyDB();
     if(!my.getConn().isClosed()){
     System.out.println("ok!");
     }else
     System.out.println("error");
    }

}


哪里不对啊,怎么链接不上数据库
MySQL

------解决方案--------------------
private String jdbcUrl="jdbc:mysql://localhost:3360/manger";
MySql的默认端口是3306,而不是3360.
别告诉我你自己改成了3360。
------解决方案--------------------
	public static Connection connectDatabase(){
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("数据库连接失败");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("数据库连接失败");
}finally{
return conn;
}
}

------解决方案--------------------
public class MyDB{
    private Connection conn=null;
    private String jdbcUrl="jdbc:mysql://localhost:3306/manger";
    private String user="root";