我正在尝试连接到数据库,并使用JSP在数据库中只插入一个值。我创建了表category
,其中包含Category_id
和Category_name
两列,其中Category_id
是自动增量。所以我想只在表格中插入类别名称。问题是,我无法插入。
以下是我写的代码:
String cname = request.getParameter("cname");
try{
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/infoshare", "root", "");
// Execute SQL query
Statement stmt = conn.createStatement();
String sql;
sql = "INSERT INTO catagory(Catagory_name) VALUES("+cname+")";
//ResultSet rs = stmt.executeQuery(sql);
//out.print(cname);
stmt.executeUpdate(sql);
out.print("<h1>Hello</h1>");
// Clean-up environment
//rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
答案 0 :(得分:1)
尝试几次之后,得到的答案如下:
String cname = request.getParameter("cname");
String cstatus = request.getParameter("cstatus");
try{
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/infoshare", "root", "");
// Execute SQL query
Statement stmt = conn.createStatement();
//
String sql;
sql = "INSERT INTO category(Category_name,status) values('"+cname+"','"+cstatus+"')";
stmt.executeUpdate(sql);
// ResultSet rs = stmt.executeQuery(sql);
response.sendRedirect("add_category.jsp");
// Clean-up environment
//rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
}