将实体插入sql数据库

时间:2017-07-05 22:49:11

标签: java mysql sql database apache

我有一个带有字段和方法的Entity Employee,我希望有一个方法可以直接将它添加到数据库中(而不是通过键入它)。但是,当我运行程序时,没有任何内容插入数据库中。有没有办法将值插入数据库?

  public void insert(Employee person) {
    Connection connection = null;
    java.sql.PreparedStatement preparedStatement = null;

    try {
        connection = getConnection();
        preparedStatement = connection.prepareStatement("INSERT INTO Employee5 (name,department)" +
                "VALUES (?,?)");
        preparedStatement.setString(1, person.getName());
        preparedStatement.setString(2, person.getDepartment());
        preparedStatement.executeUpdate();
        System.out.println("INSERT INTO Employee5 (name,department)" +
                "VALUES (?,? )");

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

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

0 个答案:

没有答案
相关问题