java连接sqlserver2019
时间: 2023-04-23 17:05:19 浏览: 94
Java可以使用JDBC连接SQL Server 2019。需要先安装SQL Server JDBC驱动,然后使用代码连接数据库。连接字符串需要指定服务器地址、端口号、数据库名称等信息。示例代码如下:
```java
import java.sql.*;
public class SqlServerConnect {
public static void main(String[] args) {
String connectionUrl =
"jdbc:sqlserver://localhost:1433;"
+ "databaseName=AdventureWorks;user=UserName;password=*****";
try (Connection con = DriverManager.getConnection(connectionUrl); Statement stmt = con.createStatement();) {
String SQL = "SELECT TOP 10 * FROM Person.Contact";
ResultSet rs = stmt.executeQuery(SQL);
while (rs.next()) {
System.out.println(rs.getString("FirstName") + " " + rs.getString("LastName"));
}
}
// Handle any errors that may have occurred.
catch (SQLException e) {
e.printStackTrace();
}
}
}
```
建议在连接数据库时使用数据库连接池,以提高性能。
阅读全文