java连接sqlserver数据库
时间: 2023-09-04 08:08:08 浏览: 41
要连接SQL Server数据库,首先需要下载并安装Microsoft JDBC驱动程序。然后,可以使用以下代码示例连接到SQL Server数据库:
```
import java.sql.*;
public class SQLServerConnectionExample {
public static void main(String[] args) {
String dbURL = "jdbc:sqlserver://localhost\\SQLEXPRESS;databaseName=myDB";
String user = "myUsername";
String password = "myPassword";
try {
Connection conn = DriverManager.getConnection(dbURL, user, password);
if (conn != null) {
System.out.println("Connected to the database!");
}
} catch (SQLException ex) {
System.out.println("Oops, something went wrong!");
ex.printStackTrace();
}
}
}
```
在此示例中,`dbURL`变量指定了SQL Server实例和要连接的数据库名称。`user`和`password`变量包含连接所需的凭据。`DriverManager.getConnection()`方法用于创建与数据库的连接,如果成功,则打印“Connected to the database!”消息。如果出现错误,则打印堆栈跟踪。