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(); } } }
原文地址:http://black4yl.blog.51cto.com/4222963/1589687