问题
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