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