your class has the same name as the class in the package java.sql that's why u have this conflict ,juste try to change the name to Connexion ,it should work
Unable to connect MS SQL server via Java Class
-
01-07-2023 - |
Domanda
I am getting error when I try to connect database
Error:com.microsoft.sqlserver.jdbc.SQLServerConnection cannot be cast to
Ptakip.Connection
- Ptakip is my Package
Connection is my Class
Here is the Connection Class Code ;
import java.sql.*; public class Connection { private Connection cn; public Connection connector( ) { try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection cn = (Connection) DriverManager.getConnection("jdbc:sqlserver://localhost\\MyServer: 1433;databaseName=TEST;user=Glassfish;password=pass;"); System.out.println("connected"); } catch(Exception ex) { System.out.println("Error:" + ex.getMessage()); System.out.println(cn); } return cn; } }
Soluzione
Altri suggerimenti
Try to make a connection like this. it may help you
String url = "jdbc:mysql://localhost:3306/";
String dbName = "demo”
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "mypasswd";
try {
Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url+dbName,userName,password);
conn.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow