如何用java写一个小程序,功能如下:可以把txt里面的数据导入到oracle数据库中

例如:txt文档里 李鹏 男 21 。。。。 很多条数据,现在要通过一个java写的小程序导入到table t_student的name,sex,age三个字段,请问这样的java怎么写,希望能运行的,在线等。

public class ReadTxt {

/**
*
* @param filePath
* 你的txt文件路径
* @param state
* @throws IOException
*/
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)),
"utf-8")));//编码方式为utf-8,txt保存时编码方式也要选择为utf-8
String instring;
String[] strArr = null;
while ((instring = bufferedreader.readLine()) != null) {
if (0 != instring.length()) {
strArr = instring.split(" ");//与txt文件中的分隔符要一致
addDataToState(strArr,state);
}
}
f.close();
}

/**
* 添加数据到state预编译语句
* @param strArr
* @param state
*/
public void addDataToState(String[] strArr, PreparedStatement state) {
try {
state.setString(1, strArr[0]);
state.setString(2, strArr[1]);
state.setString(3, strArr[3]);
} catch (SQLException e) {
e.printStackTrace();
}
}

public void saveData(String filePath) {
Connection conn = null;// 得到你的数据库连接
PreparedStatement state = null;
try {
conn.setAutoCommit(false);// 设置手动提交事务
state = conn
.prepareStatement("insert into t_student(name,sex,age) 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("");//参数为你的txt文件路径
}
}
你的txt文档格式必须是:
姓名 性别 年龄
中间用“ ”隔开,如有变动需改变程序
不懂的可以发我邮箱:ucfjepl@126.com
温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答