将txt文件内容(以utf-8)存储到数据库中
2014-03-23 15:51
417 查看
package com.test.javaSe01; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; /** * * @author Administrator * @see txt中的内容是中文的(utf-8格式),将txt中的内容存储到数据库中 */ public class JDBCClobTestDemo01 { public static void main(String[] args) throws SQLException, FileNotFoundException, ClassNotFoundException, UnsupportedEncodingException { String url = "jdbc:mysql://localhost:3306/test?unicode=true&characterEncoding=utf8"; String driver = "com.mysql.jdbc.Driver"; String user = "root"; String password = "root"; Connection conn = null; PreparedStatement ps = null; Statement st = null; ResultSet rs = null; String sql = "insert into userclob values(id,?,?)"; Class.forName(driver); File file = new File("H:\\a.txt"); InputStream input = new FileInputStream(file); Reader reader = new InputStreamReader(input, "utf-8"); conn = DriverManager.getConnection(url, user, password); try { ps = conn.prepareStatement(sql); ps.setString(1, "ctl"); // setAsciiStream() setBlob() setCharacterStream()只可以存储英文不可以存储汉字 // ps.setAsciiStream(2, input, (int) file.length()); ps.setNCharacterStream(2, reader, file.length()); ps.executeUpdate(); sql = "select * from userclob"; rs = ps.executeQuery(sql); while (rs.next()) { System.out.print(rs.getInt(1) + "\t"); System.out.print(rs.getString(2) + "\t"); // getAsciiStream(), getCharacterStream() // getString()都可以获取类型longtext中的数据 // Scanner scanner = new Scanner(rs.getAsciiStream(3)); // Scanner scanner = new Scanner(rs.getCharacterStream(3)); Scanner scanner = new Scanner(rs.getString(3)); scanner.useDelimiter("\r\n"); StringBuffer sb = new StringBuffer(); while (scanner.hasNext()) { sb.append(scanner.next()).append("\n"); } System.out.println(sb); } ps.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
相关文章推荐
- Could not load file or assembly 'System.Data.SQLite ... 试图加载格式不正确的程序
- mysql数据复制至redis的一种应用场景 bash实现
- Memcached学习(一)
- 数据库的热备份和冷备份
- Mysql Dump
- mysqli扩展库操作
- 非归档遭遇ORA-00333导致数据库无法open
- Oracle中如何恢复被删掉的存储过程?
- Mysql到Redis的数据协议
- sql 百分比
- MYSQL 基础
- 2014年第1季度Oracle PSU更新(For 10.2.0.4+版本)
- [Entity Framework] MySQL @ Entity Framework 6
- oracle使用max函数遇到的困惑
- SQL列转行
- PLSQL之DBMS_SQL程序包使用2
- mysql 忘记密码或修改密码
- Zabbix 2.2(四):监控MSSQL2005
- Python操作redis
- SQL Server 迁移数据到MySQL