Dan*_*llo 10
您可能需要查看以下示例:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class InsertPictureToMySql {
public static void main(String[] args) throws Exception, IOException, SQLException {
Class.forName("org.gjt.mm.mysql.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/databaseName", "root", "root");
String INSERT_PICTURE = "INSERT INTO MyPictures (photo) VALUES (?)";
FileInputStream fis = null;
PreparedStatement ps = null;
try {
conn.setAutoCommit(false);
File file = new File("/tmp/photo.png");
fis = new FileInputStream(file);
ps = conn.prepareStatement(INSERT_PICTURE);
ps.setBinaryStream(1, fis, (int) file.length());
ps.executeUpdate();
conn.commit();
} finally {
ps.close();
fis.close();
}
}
}
Run Code Online (Sandbox Code Playgroud)
MySQL表:
CREATE TABLE MyPictures (
photo BLOB
);
Run Code Online (Sandbox Code Playgroud)
如果映像位于MySQL服务器主机上,则可以使用LOAD_FILE()MySQL客户端的命令:
INSERT INTO MyPictures (photo) VALUES(LOAD_FILE('/tmp/photo.png'));
Run Code Online (Sandbox Code Playgroud)
读取文件的内容(BINARY)并将其插入insert\update MYSQL查询中
谷歌中有很多例子:
http://www.java2s.com/Code/Java/Database-SQL-JDBC/InsertpicturetoMySQL.htm
http://www.roseindia.net/jdbc/save_image.shtml
http://www.jguru.com/faq/view.jsp?EID=1278882