文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>java 向 mysql中插入图片----(demo)

java 向 mysql中插入图片----(demo)

时间:2008-11-26  来源:linux_wuliqiang

package com.kevin.mysql;
/*
* mysql 插入blog的例子
*
*/
import java.io.*;
import java.sql.*;
                                                    
public class DBTest {
  public static void main(String[] args) {
    String driver = "com.mysql.jdbc.Driver";
    String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=GBK";
    String user = "root";
    String password = "";
    try {
        Class.forName(driver);
        Connection conn = DriverManager.getConnection(url, user, password);

      
        File file = new File("./laurapausini.jpg");
        int length = (int) file.length();
        InputStream fin = new FileInputStream(file);

      
        PreparedStatement pstmt = conn.prepareStatement(
              "INSERT INTO files(description,filecontent) VALUES(?, ?)");
        pstmt.setString(1, "Logo");
        pstmt.setBinaryStream (2, fin, length);
        pstmt.executeUpdate();
        pstmt.clearParameters();
        pstmt.close();
        fin.close();

      /*
        * 读取blob输出到文件
        */
        Statement stmt = conn.createStatement();
        ResultSet result = stmt.executeQuery("SELECT * FROM files");
        result.next();
        String description = result.getString(1);
        Blob blob = result.getBlob(2);

        
        System.out.println("描述:" + description);
        FileOutputStream fout = new FileOutputStream("./laurapausini2.jpg");
        fout.write(blob.getBytes(1, (int)blob.length()));
        fout.flush();
        fout.close();
                                                    
        stmt.close();
        conn.close();
    }
    catch(ClassNotFoundException e) {
        System.out.println("找不到驱动");
        e.printStackTrace();
    }
    catch(SQLException e) {
        e.printStackTrace();
    }
    catch(IOException e) {
        e.printStackTrace();
    }
  }
}

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载