How to use the Java language to save a picture resource in a binary form in a database
Create a table in SQL Server
Use MYDB1
Go
CREATE TABLE Saveimg (
ID varchar (primary key),
IMG Image NOT NULL
)
Select *from saveimg
Using the Microsoft-provided sqljdbc4.jar for database storage, I started to use the Jtds found not stored, and then use the SQLJDBC, this I do not scrutiny, interested can try.
Demo for Java
Package com.ht.save;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.InputStream;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.PreparedStatement;
Import java.sql.SQLException;
public class Saveimgproc {
private static Connection Conn;
private static PreparedStatement PS;
private static FileInputStream FIS;
public static void Main (string[] args) {
Convert a picture resource to a binary resource
String UserName = "sa";
String Password = "sa";
try {
Class.forName ("Com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = Drivermanager.getconnection (
"JDBC:SQLSERVER://XXX.XX.XXX.XX:1433;DATABASENAME=MYDB1",
UserName, Password);
PS = conn.preparestatement ("INSERT into saveimg values (?,?)");
String filepath= "F:/images/p4.jpg";
InputStream Is=readimgstream (FilePath);
Ps.setstring (1, x);
Ps.setstring (1, "sp0006");
Ps.setasciistream (2, is);
int i = Ps.executeupdate ();
if (i>0) {
SYSTEM.OUT.PRINTLN ("Image resource insert succeeded");
}
} catch (Exception e) {
E.printstacktrace ();
} finally {
if (PS! = null) {
try {
Ps.close ();
} catch (SQLException e) {
E.printstacktrace ();
}
}
IF (conn! = null) {
try {
Conn.close ();
} catch (SQLException e) {
E.printstacktrace ();
}
}
}
}
/***
* Read the picture resource and convert the picture resource into a binary array
* Path to @param path picture resource
* @return File input stream
*/
public static InputStream Readimgstream (String path) {
File File = new file (path);
Assigning a value to a SQL parameter
try {
FIS = new FileInputStream (file);
} catch (FileNotFoundException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
return FIS;
}
}
Java saves picture resources in binary form to SQL Server database