我知道这已被问了一百万次,我查了100个链接都指向我正在做的事情,但我无法让这个工作。
代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ConnectMSSQLServer
{
public static void main(String[] args) {
Connection conn = null;
String dbName = "database1";
String serverip="dv-bi-olap1";
String serverport="1433";
String url = "jdbc:sqlserver://localhost:1433;" + "databaseName=AdventureWorks;user=MyUserName;password=*****;";
Statement stmt = null;
ResultSet result = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String databaseUserName = "admin";
String databasePassword = "root";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
result = null;
String pa,us;
result = stmt.executeQuery("select * from table1 ");
while (result.next()) {
us=result.getString("uname");
pa = result.getString("pass");
System.out.println(us+" "+pa);
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
CMD命令:
C:\Users\blabla\Desktop>javac ConnectMSSQLServer.java
创建了类文件
set CLASSPATH =.;C:\Users\blabla\Desktop\sqljdbc_4.2\enu\sqljdbc42.jar
C:\Users\blabla\Desktop>java ConnectMSSQLServer
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:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at ConnectMSSQLServer.main(ConnectMSSQLServer.java:21)
好的,dint工作,所以我在下面尝试
C:\Users\blabla\Desktop>java -CLASSPATH =.;C:\Users\blabla\Desktop\sqljdbc_4.2\enu\sqljdbc42.jar -cp . ConnectMSSQLServer
然后这个
C:\Users\blabla\Desktop>java -CLASSPATH =.;C:\Users\blabla\Desktop\sqljdbc_4.2\enu\sqljdbc42.jar ConnectMSSQLServer
所有导致以下错误
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:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at ConnectMSSQLServer.main(ConnectMSSQLServer.java:21)
答案 0 :(得分:2)
尝试删除=
&使用小写classpath
(或cp
)选项
java -classpath .;C:\Users\blabla\Desktop\sqljdbc_4.2\enu\sqljdbc42.jar ConnectMSSQLServer
答案 1 :(得分:1)
您需要下载驱动程序。
然后将其包含在您的应用程序中。根据您的说法,我无法看到您需要在您的应用程序中使用JBDC的驱动程序。