每次添加到数据库时如何创建新文件到文件系统

时间:2016-12-12 17:42:46

标签: java file prepared-statement

我已经创建了使用预处理语句将用户数据添加到数据库的方法。我工作得很好。现在我每次将新用户添加到数据库时如何在我的计算机上创建一个新文件夹。例如,当我单击提交按钮用户数据时正在添加到数据库中,并且正在我的文档文件夹中创建新文件夹。我尝试了各种代码,但它没有工作。我使用Linux和Net Beans 8.1。提前谢谢

这是我的方法。

public String addUser(int useId, String name, String lastName, String country, String birthplace, String adress, String password) throws SQLException {
    List<User> list = listAllUsers();
    int size = list.size();



    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    for (int i = 0; i < size; i++) {
        if (useId == list.get(i).getIdUser()) {
            return "error";
        }

    }

    conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/testBaza?user=root");
    ps = conn.prepareStatement("INSERT INTO User (id_user,name,last_name,birthplace,country,adress,user_pass) values(?,?,?,?,?,?,?)");
    conn.setAutoCommit(false);

    ps.setInt(1, useId);
    ps.setString(2, name);
    ps.setString(3, lastName);
    ps.setString(4, country);
    ps.setString(5, birthplace);
    ps.setString(6, adress);
    ps.setString(7, password);

    ps.executeUpdate();
    conn.commit();
    conn.close();



    return "userRegPage";

}

2 个答案:

答案 0 :(得分:0)

以下代码应该有效。请记住,当运行程序的uesr无权在给定路径中创建目录时,此代码会抛出SecurityException。因此,如果您正在运行Web应用程序,请使用具有足够权限的用户运行应用程序服务器。

public String addUser(int useId, String name, String lastName, String country, String birthplace, String adress, String password) throws SQLException {
    List<User> list = listAllUsers();
    int size = list.size();

    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    for (int i = 0; i < size; i++) {
        if (useId == list.get(i).getIdUser()) {
            return "error";
        }
    }

    conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/testBaza?user=root");
    ps = conn.prepareStatement("INSERT INTO User (id_user,name,last_name,birthplace,country,adress,user_pass) values(?,?,?,?,?,?,?)");
    conn.setAutoCommit(false);

    ps.setInt(1, useId);
    ps.setString(2, name);
    ps.setString(3, lastName);
    ps.setString(4, country);
    ps.setString(5, birthplace);
    ps.setString(6, adress);
    ps.setString(7, password);

    ps.executeUpdate();
    conn.commit();
    conn.close();

    String folderName = "~/MyDocuments/" + id_user; // the folder name is user_id, you can use something else as well
    new File(folderName).mkdir(); // the directory is created

    return "userRegPage";
}

答案 1 :(得分:0)

我想通了

刚刚将此代码添加到我的方法中,看起来我需要将我的用户名添加到文件路径中。

int x;// Reservation 2 or 4 bytes in memory.
相关问题