我创建了一个Java应用程序来连接MySQL数据库。 连接是以这种方式进行的:
public class Connection {
public static Connection getConexao() throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
//System.out.println("Conectado");
return DriverManager.getConnection("jdbc:mysql://localhost/world","root", "rootadmin");
} catch (ClassNotFoundException e) {
throw new SQLException(e.getMessage());
}
}
}
现在我需要将连接从MySQL更改为 Microsoft SQL Server 2012 。
有人可以帮我改变与数据库的连接吗?
非常感谢你们。
答案 0 :(得分:1)
首先,您将需要用于MS SQL Server的JDBC驱动程序。来自Microsoft或其他选项,例如jTDS。
然后你应该使用像jdbc:sqlserver://ServerName:Port;databaseName=;user=username;password=password;
当然,您的SQL Server应处于混合模式,因此您可以使用在服务器上创建的用户名和密码进行连接。
小程序在用户的计算机上运行,因此您应该向所有访问者打开SQL Server端口,这是一个不好的想法。
答案 1 :(得分:0)
Make database URL like :
jdbc:mysql://IP address:DatabasePort/DatabaseName,username, password
public class Connection {
public static Connection getConexao()throws SQLException{
try{
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/world","root", "rootadmin");
}catch(ClassNotFoundException e) {
throw new SQLException(e.getMessage());
}
}
}
答案 2 :(得分:0)
此答案针对此类问题提供给下一个访问者。可以为 SQL Server 配置Java驱动程序连接 对于新用户来说相当混乱。我将通过 SQL Management Studio(SMSS)
指导您:SQL Server接受两种身份验证。它们是 Windows 和 SQL Server 身份验证。 在此答案中,我将激活“ sa ”(系统管理员)帐户,以通过连接进行快速设置演示。
要启用“ sa ”帐户 (如果已经存在,可以跳过此帐户) :
为conn启用TCP / IP。实例(默认情况下,这是默认禁用的,尤其是在sql express版本上):
您现在可以将此凭据用于SMSS:
username : sa
password : ...the password you've just set up above..
或者您现在可以在基于外部Java的客户端/数据或 BI 工具/ sql管理工具(例如 Pentaho , Heidi SQL em>, DB Weaver 或任何特定的Java框架conn。经理描述符等:
hostname : localhost (or any custome host domains)
database name : your database name..
instance name : i.e SQLEXPRESS (this can be found through the SMSS, right click the server name > view connection properties)
port : 1433
username : sa
password : ...the password you've just set up above..
或通过url / uri用于Java连接管理器/工厂:
String Connectionurl="jdbc:sqlserver://localhost:1433;DatabaseName=Yourdatabasename;user=sa;password=yourSApassword";
public Connection createConnection() throws NoSuchAlgorithmException {
System.out.println("Creating SQL Server DataBase Connection");
Connection connection = null;
try {
// Provide the java database driver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// Provide URL, database and credentials according to your database
// .getConnection ("url/namadatabase, user, password")
String Connectionurl="jdbc:sqlserver://localhost:1433;DatabaseName=DummyDatabase;user=sa;password=YourSAaccountpassword";
connection = DriverManager.getConnection(Connectionurl);
} catch (Exception e) {
e.printStackTrace();
return null;
}
if (connection != null) {
System.out.println("Connection created successfully..");
}
return connection;
}