Java文件链接SQL数据库
时间: 2023-06-15 15:05:35 浏览: 49
要连接SQL数据库,可以使用Java中的JDBC(Java Database Connectivity)API。以下是在Java中连接SQL Server数据库的示例代码:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SQLConnection {
public static void main(String[] args) {
Connection conn = null;
try {
// 加载数据库驱动
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// 连接数据库
String url = "jdbc:sqlserver://localhost:1433;databaseName=mydatabase";
String user = "username";
String password = "password";
conn = DriverManager.getConnection(url, user, password);
// 连接成功
System.out.println("数据库连接成功");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
```
在上面的示例代码中,我们首先通过 `Class.forName()` 方法加载SQL Server数据库驱动程序。然后使用 `DriverManager.getConnection()` 方法连接到数据库。连接字符串 `url` 包括了数据库地址、端口和数据库名称,`user` 和 `password` 分别是数据库的用户名和密码。最后,我们在 `finally` 块中关闭数据库连接。
注意,要将 `com.microsoft.sqlserver.jdbc.SQLServerDriver` 添加到项目的 classpath 中,否则会出现 ClassNotFoundException。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)