java.sql.SQLException: No suitable driver found for jdbc:sqlserver [duplicate]

核能气质少年 提交于 2019-12-08 09:25:48

问题


I am working on a web application where I am creating MSSQLSERVER 2008 database dynamically.

But it's giving me

java.sql.SQLException: No suitable driver found for jdbc:sqlserver://localhost:1433;databaseName=master

My code is:

String dbName = "db1";
try {
    String url = "jdbc:sqlserver://localhost:1433;databaseName=master";
    Connection connection = DriverManager.getConnection(
                 url,
                 "sa",
                 "roshan14121987");

    Statement statement = connection.createStatement();
    String sqlquery = "CREATE Database \"" + dbName + "\"; ";
    statement.executeUpdate(sqlquery);
    statement.close();

    connection.close();

} catch(Exception e) {
    e.printStackTrace(); 
}

I have added sqljdbc4.jar in lib. I have tried it on both NetBeans (with GlassFish and Tomcat Server) and Eclipse IDE(Tomcat Server).

On the other hand I have tried this with simple desktop application, it's working fine on both IDEs. With sqljdbc4.jar added in lib.


回答1:


Before calling DriverManager.getConnection() you will have to load the SQLServer JDBC driver. You can do Class.forName("xxxx"); where xxxx is the appropriate driver class (fully qualified name with package prefix).

EDIT: Do this Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); to load the driver. Refer MSDN link for more.




回答2:


Is sqljdbc4.jar in your war file under WEB-INF/lib. This is the alternate location to $CATALINA_HOME/lib and recommended to keep your web application self-contained. Further, if you should ever need to change servers, you need only drop the war into your webapps directory.

You might also need a Class.forName([database class]).newInstance, but that isn't necessary using a JDBC 4.0 driver. Good luck and if you have further problems, do leave a comment.




回答3:


The error happen in the runtime on Tomcat Server,right? I think you need to make sure your sqljdbc4.jar deploy the in the Server.



来源:https://stackoverflow.com/questions/17760024/java-sql-sqlexception-no-suitable-driver-found-for-jdbcsqlserver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!