【发布时间】:2018-07-26 04:10:03
【问题描述】:
我快疯了,现有的解决方案似乎都不适合我。我是老派,所以只需在 NotePad++/EditPlus 中编码并通过 CLI 编译。我有一个超级通用的 DB.JAVA 文件,我无法通过加载 SQL 驱动程序类的尝试。我很茫然,希望其他人可以提供帮助。从长远来看,这将在 Tomcat 上的 JSP 中使用。
Java 版本:1.8.0_181 或 10.0.2(我都有,x64 版本)
SQL Server:2017 Express
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用于编译,此处传递的选项对您的运行方式没有影响。 那么,你是怎么运行它的?您是否传递了classpath的值? -
按照javadocs尝试设置这种格式
java -classpath C:\java\MyClasses\myclasses.jar utility.myapp.Cool -
看起来你仍然需要将
./添加到你的类路径中,但是说真的,你为什么不保护自己的痛苦并下载像eclipse这样的免费IDE? -
@MichaelLowden IDE 需要加载的时间与它通过帮助识别错误并显示错误发生的位置和原因所节省的时间相比是可以忽略不计的。
-
@Gaurav 这是非常糟糕的建议。
lib/ext文件夹从未用于该用途,它已被弃用,并已在较新的 Java 版本中被删除。
标签: java sql-server jdbc driver