mysql插入文本文档及读取

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();
}
}

转载于:https://www.cnblogs.com/wzk1992/p/5735569.html

你可能感兴趣的:(mysql插入文本文档及读取)