我在将sqlserver与jdbc连接时遇到麻烦。我试图用很多提示谷歌修复它,但没有成功。错误是:
“无法打开登录名请求的数据库“ ShoppingWeb”。登录名 失败了ClientConnectionId:0a0dc93b-85e3-46d1-89f8-045bde4984c5“
请帮帮我。 Tks阅读!
这是我的代码:
public class ConnectDB {
public ConnectDB() {
}
private static String DB_URL = "jdbc:sqlserver://localhost;"
+ "databaseName=ShoppingWeb;"
+ "integratedSecurity=true";
private static String USER_NAME = "sa";
private static String PASSWORD = "123";
public static void main(String[] args){
try {
// i had aslo try with
//Connection con = getConnection(DB_URL, USER_NAME, PASSWORD);
// but i got the same error
Connection con = getConnection(DB_URL);
Statement stmt;
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from DanhMuc");
// show data
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2)
+ " " + rs.getString(3));
}
// close connection
con.close();
} catch (SQLException ex) {
Logger.getLogger(ConnectDB.class.getName()).log(Level.SEVERE, null, ex);
}
}
// public static Connection getConnection(String dbURL, String userName,
String password) throws SQLException
public static Connection getConnection(String dbURL) throws SQLException {
Connection con = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// con = DriverManager.getConnection(dbURL, userName, password);
con = DriverManager.getConnection(dbURL);
System.out.println("Connect success");
} catch (ClassNotFoundException ex) {
Logger.getLogger(ConnectDB.class.getName()).log(Level.SEVERE, null, ex);
}
return con;
}
}
答案 0 :(得分:-2)
也许,您可以尝试以下方法:
private static String DB_URL = "jdbc:mysql://HOST:PORT/DB_NAME?useUnicode=true&characterEncoding=UTF-8&useSSL=true";
private static String USER_NAME = "USE_NAME";
private static String PASSWORD = "PASSWORD";
@Test
public void contextLoads() {
try {
Connection con = getConnection(DB_URL);
Statement stmt;
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from user");
// show data
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2)
+ " " + rs.getString(3));
}
con.close();
} catch (SQLException ex) {
}
}
public static Connection getConnection(String dbURL) throws SQLException {
Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection(dbURL, USER_NAME, PASSWORD);
System.out.println("Connect success");
} catch (ClassNotFoundException ex) {
}
return con;
}