Java中如何把图片保存到sql server
时间: 2024-03-25 08:38:36 浏览: 26
在Java中,可以使用JDBC连接SQL Server数据库,并将图片以二进制数据的形式存储到数据库中。以下是一个简单的示例代码:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class SaveImageToSQLServer {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
FileInputStream fis = null;
try {
// 1. 加载SQL Server JDBC驱动程序
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// 2. 连接SQL Server数据库
String url = "jdbc:sqlserver://localhost:1433;databaseName=mydb";
String user = "sa";
String password = "mypassword";
conn = DriverManager.getConnection(url, user, password);
// 3. 准备SQL语句
String sql = "INSERT INTO Images (name, data) VALUES (?,?)";
pstmt = conn.prepareStatement(sql);
// 4. 读取图片文件
File imageFile = new File("C:\\image.jpg");
fis = new FileInputStream(imageFile);
byte[] imageData = new byte[(int) imageFile.length()];
fis.read(imageData);
// 5. 设置SQL语句参数
pstmt.setString(1, imageFile.getName());
pstmt.setBytes(2, imageData);
// 6. 执行SQL语句
int rows = pstmt.executeUpdate();
System.out.println(rows + " rows affected");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 7. 关闭数据库连接和输入流
try {
if (fis != null) {
fis.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
以上代码将指定路径下的图片文件以二进制形式读取并插入到名为Images的数据库表中。其中,name列存储图片文件名,data列存储图片的二进制数据。可以根据实际需要修改表名、列名和SQL语句。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)