Prepared语句不执行

Prepared语句不执行

本文介绍了Java Prepared语句不执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
p>您应该在语句对象上调用方法 executeUpdate()



任何调用提交数据,任何事务处理。如果你跳过这段代码的目的这个问题的很好;否则这是相当重要的一步(如果一切顺利,提交,回退异常情况)


I have created a small 3 tier program, consisting of : front end -> servlet -> database.

Front end I enter some details into a form. They are passed to a servlet, which will render some HTML and display the values entered into the form, while also calling a class DatabaseHelper. The DatabaseHelper then connects and inserts these same values into a table.

I know the values are being passed to the servlet class ok, as they are being displayed in the HTML. So the problem must lie within the prepared statement. Problem is, I cannot see any fault with the statement itself. When I query the table itself, there is no data there.

Database connectivity is functional, as I can insert values into a database using hardcoded statements, just not a prepared statement.

Here is a look at the statement Im using. Any advice is much appreciated.

    public void addRegisterDetails(String name, String email, String country, String password, ){
    try{
        String driver = "com.mysql.jdbc.Driver";
        Class.forName(driver).newInstance();
        // Make db connection
        con = DriverManager.getConnection(url, USERNAME, PASSWORD);
        st  = con.createStatement();


        String query = " INSERT INTO user_information (name, email, country, password)" + " VALUES (?, ?, ?, ?)";
        PreparedStatement preparedStmt = con.prepareStatement(query);
        preparedStmt.setString (1, name);
        preparedStmt.setString (2, email);
        preparedStmt.setString (3, country);
        preparedStmt.setString (4, password);
        preparedStmt.execute();

    }catch(ClassNotFoundException ex) {
        System.out.println(ex);
    }catch(Exception e){
         e.printStackTrace();
    }
}

Table definition

id| name | email | country | password

all VARCHAR except the id, which is type INT.

解决方案

You should invoke the method executeUpdate() on the statement object.

Also, I don't see any call to commit the data, any transaction handling. It's fine if you skipped that piece of code for the purpose of this question; otherwise it's quite an important step ( commit if all goes well, rollback for exception scenarios)

这篇关于Java Prepared语句不执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 01:42