java - java.sql.SQLException: 找不到合适的驱动程序 (SQL Server Express)
问题描述
我快疯了,现有的解决方案似乎都不适合我。我是老派,所以只需在 NotePad++/EditPlus 中编码并通过 CLI 编译。我有一个超级通用的 DB.JAVA 文件,我无法通过加载 SQL 驱动程序类的尝试。我很茫然,希望其他人可以提供帮助。从长远来看,这将在 Tomcat 上的 JSP 中使用。
Java 版本:1.8.0_181 或 10.0.2(我都有,x64 版本)
SQL Server : 2017 速成版
JDBC JAR:mssql-jdbc-6.4.0.jre8.jar(目前在与 DB.java 相同的目录中)
我的基本代码:
import java.sql.*;
import com.microsoft.sqlserver.jdbc.*;
public class DB {
public static void main(String[] args) {
// Create a variable for the connection string.
String connectionURL = "jdbc:microsoft:sqlserver://HomeServer:1433;databaseName=MY_FIRST_DB";
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// I've read this isn't needed anymore as the DriverManager is smart enough
// It will fail on this line, or the next if I comment it out with the same error
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionURL,"sa","xxxxxxxxxxxx");
// Create and execute an SQL statement that returns a
// set of data and then display it.
String SQL = "SELECT * FROM v_Users";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next()) {
System.out.println(rs.getString("Username") + ":" + rs.getString("Email"));
}
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
}
}
编译:很好"%JAVA_HOME%"/bin/javac.exe -cp ./* DB.java
跑:"%JAVA_HOME%"\bin\java.exe -cp ./ DB
当我运行它时出错,不管-cp
我给它什么。如果我评论 Class.forName 然后我得到一个通用的“找不到合适的驱动程序”:
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at DB.main(DB.java:19)
解决方案
编译代码的正确方法是:
javac -cp .;mssql-jdbc-6.4.0.jre8.jar DB.java
运行代码的正确方法是:
java -cp .;mssql-jdbc-6.4.0.jre8.jar DB
两者都假定DB.java
并且mssql-jdbc-6.4.0.jre8.jar
位于当前目录中,并且您使用的是 Java 8。
您当然还需要修复连接 URL,即删除microsoft
:
String connectionURL = "jdbc:sqlserver://HomeServer:1433;databaseName=MY_FIRST_DB";
这一切都记录在这里:https ://docs.microsoft.com/en-us/sql/connect/jdbc/using-the-jdbc-driver?view=sql-server-2017
推荐阅读
- ruby-on-rails - 从数组的哈希中创建多条记录
- angular - 如何将表单发送到父组件
- react-admin - 如何支持在资源显示布局上查看其他资源数据
- uwp - 适用于 UWP 应用程序的 Google Cloud Speech API
- c# - 模型类与 DTO 的 Post Action
- tensorflow - 如何在 Mac 上安装 TensorFlow?
- mysql - 尝试将分数分配给列时接收空值
- python - Discord API 401:未经授权的错误
- scala - 适用于 Apache Spark 的 BigQuery 连接器 - 更新分区表
- r - 如何从 rvest 中的元素中刮取 id?