從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");
	}
}
相關文章
相關標籤/搜索