当前位置: 技术问答>java相关
谁能帮我看看下面的代码有什么错误,我是初学者。
来源: 互联网 发布时间:2015-11-01
本文导语: 谁能帮我看看下面的代码有什么错误,我是初学者。用的是本地机子上的数据库,是sql自带的。用户名和密码没设。 import java.sql.*; public class trySQLServer{ public static void main(String[] arg){ try{ Class.forName("com.m...
谁能帮我看看下面的代码有什么错误,我是初学者。用的是本地机子上的数据库,是sql自带的。用户名和密码没设。
import java.sql.*;
public class trySQLServer{
public static void main(String[] arg){
try{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
String sourceURL=new String("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=e:/Program Files/Microsoft SQL Server/MSSQL/Data/pubs");
Connection databaseConnection=DriverManager.getConnection(sourceURL,"sa","");
System.out.println("Successfully connected!!");
Statement statement=databaseConnection.createStatement();
ResultSet artistNames=statement.executeQuery("SELECT au_id,au_name "+"FROM authors");
while (artistNames.next())
{
System.out.println(artistNames.getString("au_id")+" "+artistNames.getString("au_name"));
}
databaseConnection.close();
}
catch (ClassNotFoundException cnfe)
{
System.err.println(cnfe);
}
catch (SQLException sqle)
{
System.err.println(sqle);
}
}
}
调试的结果显示:
H:begjavadb>javac trySQLServer.java
H:begjavadb>java trySQLServer
java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]Log
in failed for user 'sa'. Reason: Not associated with a trusted SQL Server connec
tion.
问题在哪里呢?
import java.sql.*;
public class trySQLServer{
public static void main(String[] arg){
try{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
String sourceURL=new String("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=e:/Program Files/Microsoft SQL Server/MSSQL/Data/pubs");
Connection databaseConnection=DriverManager.getConnection(sourceURL,"sa","");
System.out.println("Successfully connected!!");
Statement statement=databaseConnection.createStatement();
ResultSet artistNames=statement.executeQuery("SELECT au_id,au_name "+"FROM authors");
while (artistNames.next())
{
System.out.println(artistNames.getString("au_id")+" "+artistNames.getString("au_name"));
}
databaseConnection.close();
}
catch (ClassNotFoundException cnfe)
{
System.err.println(cnfe);
}
catch (SQLException sqle)
{
System.err.println(sqle);
}
}
}
调试的结果显示:
H:begjavadb>javac trySQLServer.java
H:begjavadb>java trySQLServer
java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]Log
in failed for user 'sa'. Reason: Not associated with a trusted SQL Server connec
tion.
问题在哪里呢?
|
好象是用户名密码不对吧
|
单步调试一下, 看是哪句调用出错
|
1.你必须对你的数据库进行驱动。
2.你的用户名sa不是合法的用户。可以去掉sourceURL,"sa",""后的,"sa",""
2.你的用户名sa不是合法的用户。可以去掉sourceURL,"sa",""后的,"sa",""