下面是我使用jdbc对Sql Server进行简单选择查询的代码。
import java.sql.*;
import java.util.*;
public class DateServer{
public void dbconnect(String conn, String user, String pass){
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection(conn, user, pass);
System.out.println("connected");
Statement stat = con.createStatement();
String query = "select * from headcount_new";
ResultSet rs = stat.executeQuery(query);
}
catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args){
DateServer conserver = new DateServer();
conserver.dbconnect("jdbc:sqlserver://<<hostname>>", "<<username>>", "<<password>>");
}
}
我收到以下错误:
com.microsoft.sqlserver.jdbc.SQLServerException: The connection string contains a badly formed name or value.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:171)
at com.microsoft.sqlserver.jdbc.Util.parseUrl(Util.java:420)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.parseAndMergeProperties(SQLServerDriver.java:856)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:838)
at java.sql.DriverManager.getConnection(DriverManager.java:579)
at java.sql.DriverManager.getConnection(DriverManager.java:221)
at DateServer.dbconnect(DateServer.java:9)
at DateServer.main(DateServer.java:22)"
有人可以帮我解决错误吗?我是Java的新手。
感谢。
答案 0 :(得分:4)
不确定为什么你有<<hostname>>
等
JDBC URL如下所示
jdbc:sqlserver://SomeServer;user=SomeUser;password=XXX;
答案 1 :(得分:2)
这与java无关。在您的连接字符串中,您必须使用实际值替换“&lt; hostname&gt;”,“&lt; username&gt;”等。请参阅此处了解有效语法:http://www.java2s.com/Tutorial/Java/0340__Database/AListofJDBCDriversconnectionstringdrivername.htm