標籤:資料庫存入圖片 java
import java.io.FileInputStream;import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class JDBCTest { public static void main(String[] args) throws IOException { String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://127.0.0.1:3306/tuzi?characterEncoding=UTF-8"; String user = "root"; String pass = ""; try { Class.forName(driver); //載入驅動 //串連資料庫 Connection conn = DriverManager.getConnection(url,user,pass); if(!conn.isClosed()) { System.out.println("Connection Success!"); //statement 用來執行sql語句 Statement statement = conn.createStatement(); //要執行的sql String sql = "select * from BST"; //結果集 ResultSet rs = statement.executeQuery(sql); String tuzi = null; String luobo = null; while(rs.next()) { tuzi = rs.getString("tuzi"); //tuzi是個int型 主鍵 luobo = rs.getString("luobo"); //這個是blob 型 System.out.println(tuzi +" " +luobo); } /* 這個不行.... FileInputStream fis = new FileInputStream("C:\\6140\\mysql\\src\\tuzi.jpeg"); byte[] rtt = new byte[fis.available()]; fis.read(rtt); fis.close(); */ String sqlxx = "insert into BST(tuzi,luobo) values (?,?)"; PreparedStatement pstmt=conn.prepareStatement(sqlxx); FileInputStream fi=new FileInputStream("C:\\6140\\mysql\\src\\tuzi.jpeg"); pstmt.setInt(1, 521521); //pstmt.setBinaryStream(2,fi,fi.available()); 也行 pstmt.setBlob(2,fi,fi.available()); //也行 pstmt.execute(); conn.close(); } }catch(ClassNotFoundException e) { } catch (SQLException e) { e.printStackTrace(); } }}
將圖片存入資料庫【java實現】