码迷,mamicode.com
首页 > 数据库 > 详细

mysql插入文本文档及读取

时间:2016-08-04 10:26:20      阅读:318      评论:0      收藏:0      [点我收藏+]

标签:

1、把本地的一个文件插入到数据库中,数据库字段用text保存

public static void main(String[] args) {

PropKit.use(“pro.txt”);
DruidPlugin druid = new DruidPlugin(PropKit.get(“jdbcUrl”), PropKit.get(“user”), PropKit.get(“password”));
druid.start();
ActiveRecordPlugin arp = new ActiveRecordPlugin(druid);
arp.start();
Connection conn = null;
PreparedStatement st = null;
try {
conn= DbKit.getConfig().getConnection();
String sql = “insert into test(name) values(?)”;
st = conn.prepareStatement(sql);
String path =”1.text”;
File file = new File(path);
st.setCharacterStream(1, new FileReader(file), file.length());
int num = st.executeUpdate(); //执行向数据库中插入
if(num > 0) {
System.out.println(“插入成功”);
}
} catch (Exception e) {
e.printStackTrace();
}
}

2、从数据库中读取内容,然后以文本的形式保存到本地

public static void main(String[] args) {
PropKit.use(“pro.txt”);
DruidPlugin druid = new DruidPlugin(PropKit.get(“jdbcUrl”), PropKit.get(“user”), PropKit.get(“password”));
druid.start();
ActiveRecordPlugin arp = new ActiveRecordPlugin(druid);
arp.start();
Connection conn = null;
PreparedStatement st = null;
ResultSet rs=null;
try {
conn= DbKit.getConfig().getConnection();
String sql = “select name from test where id=?”;
st = conn.prepareStatement(sql);
st.setInt(1, 1);
rs = st.executeQuery(); //执行sql语句
if(rs.next()){
Reader reader = rs.getCharacterStream(“name”); //获取字段未name的项,也就是我们刚刚存到数据库的1.txt文件
char buffer[] = new char[1024];
int len = 0;
FileWriter out = new FileWriter(“D:\\1.txt”); //写到D盘下
while((len = reader.read(buffer)) > 0){
out.write(buffer, 0, len);
}
out.close();
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}

mysql插入文本文档及读取

标签:

原文地址:http://www.cnblogs.com/wzk1992/p/5735569.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!