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

编写连接数据库类的写法问题?
写了一个连接数据库类,开始是这样写的:
public   class   OrderPizzaDB
{
        private   static   String   dbUrl   =   "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs ";
        private   static   String   dbUser   =   "sa ";
        private   static   String   dbPwd   = " ";
       
        public   OrderPizzaDB()   throws   Exception
        {
              Class.forName( "com.microsoft.jdbc.sqlserver.SQLServerDriver ").newInstance();

        }
       
       
        /**
          *   获取连接
          *   @return
          *   @throws   Exception
          */
        public   static   Connection   getConnection()   throws   Exception
        {
                return   DriverManager.getConnection(dbUrl,dbUser,dbPwd);
        }
会报SQLException----No   suitable   driver
改为了:
public   class   OrderPizzaDB
{
        private   static   String   dbUrl   =   "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs ";
        private   static   String   dbUser   =   "sa ";
        private   static   String   dbPwd   = " ";
       
        public   OrderPizzaDB()   throws   Exception
        {
             
        }
       
       
        /**
          *   获取连接
          *   @return
          *   @throws   Exception
          */
        public   static   Connection   getConnection()   throws   Exception
        {
                Class.forName( "com.microsoft.jdbc.sqlserver.SQLServerDriver ").newInstance();
                return   DriverManager.getConnection(dbUrl,dbUser,dbPwd);
        }
就不会出现错误了,这里有点不太理解。

------解决方案--------------------
建立JDBC连接之前,必须向DriverManager注册driver

Class.forName( "com.microsoft.jdbc.sqlserver.SQLServerDriver ")
语句执行之后,正好会完成driver的注册。
------解决方案--------------------
同意楼上的,建立JDBC连接之前,必须向DriverManager注册driver,你的第一种写法,它无法识别driver。
------解决方案--------------------
学习了....