代码如下:
package ch13;import java.sql.*;
public class UseDriverManager {
public static void main(String args[]){
String url="jdbc:mysql://localhost/sql_test";
String userName="root";
String password="sinopatic";
Connection conn=null;

try{
System.out.println("Before the first time connect to Database");
conn=DriverManager.getConnection(url,userName,password);
System.out.println("After the first time connect to Database");
}
catch(SQLException e){
System.out.println("There are some problems occur when first connect to database");
}
if(conn==null)
System.out.println("First connection fail...");
else 
System.out.println("First connection successful!");

try{
System.out.println("\n Before mount the driver");
Class.forName("com.mysql.jdbc.Driver");
System.out.println("After mount the driver");
}
catch(ClassNotFoundException e){
System.out.println("There are some problems occur when mount the driver...");
}

try{
        conn = null;
System.out.println("\n Before the sencond time connecting the the Database");
conn=DriverManager.getConnection(url,userName,password);
System.out.println("After the second time connect to the Database");
}
catch(SQLException e){
System.out.println("There are some problems occur when first connect to database");

}
if(conn==null)
System.out.println("Sencond connection fail...");
else 
System.out.println("Second connection successful!");

try{
conn.close();
}
catch(SQLException e){
System.out.println("There are some problems occur when close the connection to the Database");
}
}
}------------------------
启动mysql,在eclipse中运行,连接不上:
ClassNotFoundException
Insert SQLException
Exception in thread "main" java.lang.NullPointerException
at ch13.UseDriver.main(UseDriver.java:33)

解决方案 »

  1.   

    必须先加载驱动Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");,从而才能交由驱动管理器控制.
      

  2.   

    Class.forName("com.mysql.jdbc.Driver");
    ----
    放前面去
    try catch太多了,直接在main上throw掉,然后去掉try catch便于测试
      

  3.   

    1.mysql的默认连接端口是3306,而你的连接字符串没有加上端口号.
    将String url="jdbc:mysql://localhost/sql_test";
    改为String url="jdbc:mysql://localhost:3306/sql_test";
    试试
    2.看看你有没有引mysql的jar包!
      

  4.   

    1这是jdbc的驱动!下载mysql-connector-java-3.1.10-bin.jar
    2设置jdbc的classpath
           SET CLASSPATH=.;%JAVA_HOME%\mysql-connector-java-3.1.10-bin.jar
    3程序中加载驱动Class.forName
    4个人建议:先测试加载的驱动是否成功!然后再接着下一步!呵呵一步一步来了!呵呵!
    http://my.6cncn.cn
    6cncn.cn
    [email protected]
      

  5.   

    用了eclipse就别设什么环境变量了,eclipse自己有个包管理的,把包添加到user library,然后在工程里导入就可以了