如何将文件内容添加到数据库?

时间:2013-09-10 11:21:21

标签: java mysql file insert filereader

我的文本文件如下:

    george   19   180     75
    paul     20   182     84
    laura    21   176     73
    ...      ...  ...     ...

我想阅读此文件并将其内容添加到我的数据库中包含参数(名称,年龄,身高,体重)的表中。名称george,paul,laura应该添加到姓名等。 我写了这样的代码。

    public static void main(String[] args) throws IOException {

    PreparedStatement preparedstatement = null;

    try{
        String read=null;
        in = new BufferedReader(new FileReader("patientlist.txt")); 
        while ((read = in.readLine()) != null) {
            String[] splited = read.split("\\s+");
            name=splited[0];
            age=splited[1];
            height=splited[2];
            weight=splited[3];       
        }
        try {
            addpatient(connection, preparedstatement, name, age, height, weight);   
            if (connection != null)
            try{connection.close();} catch(SQLException ignore){}
            }
        catch (SQLException error) {System.out.println(error);} 
    }

    catch (IOException e) {System.out.println("There was a problem: " + e);}        
    }

    public static void addpatient(Connection connection, PreparedStatement preparedstatement, String name, String age2, String height2, String weight2) throws SQLException{
    preparedstatement=connection.prepareStatement("insert into allpatients(name, age, height, weight) values(?,?,?,?)");
    preparedstatement.setString(1, name);
    preparedstatement.setString(2, age);
    preparedstatement.setString(3, height);
    preparedstatement.setString(4, weight);
    preparedstatement.executeUpdate();

}

我认为问题在于我的while循环,也许我必须添加一个for循环我无法做到这一点,我不是一个非常优秀的程序员,我很感激帮助。谢谢!

2 个答案:

答案 0 :(得分:1)

while ((read = in.readLine()) != null) {
            String[] splited = read.split("\\s+");
            name=splited[0];
            age=splited[1];
            height=splited[2];
            weight=splited[3];   
            addpatient(connection, preparedstatement, name, age, height, weight);   
         }

if (connection != null)
            try{connection.close();} catch(SQLException ignore){}
            }

addpatient()放在while循环中,然后只调用它。

答案 1 :(得分:0)

你做错了。你需要做的是在循环中将值添加到preparestatement,然后在循环中执行语句

preparedstatement = //Initialize
while(condition){
   preparedstatement.setString(1, name);
   preparedstatement.setString(2, age);
   preparedstatement.setString(3, height);
   preparedstatement.setString(4, weight);
   preparedstatement.addBatch();
}
preparedstatement.executeBatch();