插入查询不能在jsp中工作

时间:2013-01-30 14:35:16

标签: mysql jsp prepared-statement

我想在查询中使用insert语句,但输出显示Unable to connect database。 我用这个表格:

<form class="form-signin" action="CreateTeam.jsp">
                <h2 class="form-signin-heading">Create new team</h2>
                <input type="text" class="input-block-level" placeholder="Team name" name="name" id="name" required />
                <input type="text" class="input-block-level" placeholder="Team description" name="desc" id="desc" required />
                <button class="btn btn-large btn-primary" type="submit" >Create!</button>
                </form>

我的jsp代码是:

<%
                String name = request.getParameter("name");
                String desc = request.getParameter("desc");

                Connection connection = null;
                PreparedStatement pstatement = null;
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                int updateQuery = 0;
                if (name != null && desc != null) {
                    if (name != "" && desc != "") {

                        try {
                            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
                            String queryString1 = "insert into teams (name,desc) values (?, ?)";
                            pstatement = connection.prepareStatement(queryString1);
                            pstatement.setString(1, name);
                            pstatement.setString(2, desc);
                            updateQuery = pstatement.executeUpdate();
                            if (updateQuery != 0) {
                                response.sendRedirect("../AdministrationControlPanel.jsp");
                            }
                        } catch (Exception ex) {
                            out.println("Unable to connect to database.");

                        } finally {
                            pstatement.close();
                            connection.close();
                        }
                    }
                }
            %>

数据库test正在localhost上运行。我正在修改它,但我不知道,问题出在哪里。

2 个答案:

答案 0 :(得分:1)

在您的一个专栏中,

DESC是一个MySQL保留关键字。你应该使用反引号来逃避它,

INSERT INTO teams (name,`desc`) values (?, ?)

为了避免将来出现问题,避免使用属于MySQL预留关键字的关键字要好得多。

答案 1 :(得分:1)

descMySQL的关键字,您必须引用它。