从txt文本读取数据插入数据库

public class ReadTxt
{

	public void readTxt(String filePath, PreparedStatement state)
			throws IOException
	{
		FileReader f = new FileReader(filePath);
		BufferedReader bufferedreader = new BufferedReader(
				(new InputStreamReader(new FileInputStream(new File(filePath)))));
		String instring;
		String[] strArr = null;
		while ((instring = bufferedreader.readLine()) != null)
		{
			if (0 != instring.length())
			{
				strArr = instring.split("\\|");// 与txt文件中的分隔符要一致
				addDataToState(strArr, state);
			}
			
		}
		f.close();
	}

        SimpleDateFormat sdf = new SimpleDateFormat("yyyymmdd");

	public void addDataToState(String[] strArr, PreparedStatement state)
	{
		try
		{
                        state.setString(1, strArr[0]);
			state.setInt(2, Integer.parseInt(strArr[1]));
                        java.sql.Date date = new java.sql.Date(sdf.parse(strArr[5]));//Date必须转换
                        state.setDate(3, date);
			state.execute();//别忘了这句话
	
		} catch (SQLException e)
		{
			e.printStackTrace();
		}
	}

	public void saveData(String filePath)
	{
		Connection conn = null;// 得到数据库连接
		PreparedStatement state = null;
		try
		{
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn =          DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl","scott","tiger");
			conn.setAutoCommit(false);// 设置手动提交事务
			state = conn.prepareStatement("insert into worker(name,sal,job) values(?,?,?)");
			this.readTxt(filePath, state);// 第一个参数为txt文件路径
			conn.commit();// 提交数据
		} catch (Exception e)
		{
			e.printStackTrace();
		} finally
		{
			close(conn, state);
		}
	}

	public void close(Connection conn, PreparedStatement state)
	{
		try
		{
			if (conn != null)
			{
				conn.close();
				conn = null;
			}
			if (state != null)
			{
				state.close();
				state = null;
			}
		} catch (SQLException e)
		{
			e.printStackTrace();
		}

	}

	public static void main(String[] args)
	{
		ReadTxt rt = new ReadTxt();
		rt.saveData("./demo.txt");
	}
}

转载于:https://my.oschina.net/u/225831/blog/85432

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值