将txt文件内容(以utf-8)存储到数据库中

本文介绍如何使用Java处理UTF-8编码的文本文件,并将其存储到MySQL数据库中CLOB字段的方法。通过示例代码展示了从文件读取数据、设置字符流及查询返回的数据。
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();
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值