[英]Reading to text file from MySQL
我正在尝试将文本文件存储在MySQL数据库中,并在需要时将其保存到文件中。
要保存文件,我要做:
public void saveFile_InDB(File file)
{
try {
String sql = "INSERT INTO sent_emails (fileName, time, clientName) values (?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, new Date().toString());
statement.setString(2, new Date().toString());
InputStream inputStream = new FileInputStream(file);
statement.setBinaryStream(3, inputStream);
int row = statement.executeUpdate();
if (row > 0) {
System.out.println("File saved sucessfully.");
}
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
并获取并保存文件:
public void retrieveFile_fromDB()
{
try {
Statement stmt = (Statement) conn.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM sent_emails WHERE clientName='sally'");
FileOutputStream fos = new FileOutputStream("file.txt");
if (res.next()) {
Blob File = (Blob) res.getBlob("fileName");
InputStream is = File.getBinaryStream();
int b = 0;
while ((b = is.read()) != -1) {
fos.write(b);
}
fos.flush();
}
} catch (IOException e) {
e.getMessage (); e.printStackTrace();
System.out.println(e);
} catch (SQLException e) {
e.getMessage (); e.printStackTrace();
System.out.println(e);
}
}
存储文件是可行的,但是当我尝试检索和保存文件时,输出文件中没有存储任何内容吗?
如果要从db Mysql读取文件,请在代码中更改此部分
Blob File = (Blob) res.getBlob("fileName");
InputStream is = File.getBinaryStream();
int b = 0;
while ((b = is.read()) != -1) {
fos.write(b);
}
fos.flush();
使用此代码读取字节数组
byte [] bs=res.getBytes("fileName");
fos.write(bs);
如果您从db返回多个文件,则必须声明
FileOutputStream fos = new FileOutputStream("file.txt");
在while循环内部,并更改文件名以避免覆盖
您似乎没有将列名描述的内容放入数据库中?
例如, fileName
和time
都设置为时间戳,而clientName
设置为文件的内容。 当您以后尝试基于clientName
选择时,实际上是在基于文件的内容进行选择。
此外,在读取数据时,您正在从fileName
列读取blob数据,但这是错误的,因为:
fileName
包含new Date().toString()
,而不是文件的内容 fileName
是否一定包含文件名 ,而不是内容?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.