response.setContentType("text/html");
PrintWriter out = response.getWriter();
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "Employee";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "1234";
int Empid =Integer.parseInt(request.getParameter("Empid").toString());
String Name = request.getParameter("Name").toString();
int Age =Integer.parseInt(request.getParameter("Age").toString());
int Salary =Integer.parseInt(request.getParameter("Salary").toString());
Statement stmt;
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
ArrayList al=null;
ArrayList userList =new ArrayList();
String query = "insert into employee set Empid='"+Empid+"',name='"+Name+"',Age='"+Age+"',Salary='"+Salary+"'";
stmt = conn.createStatement();
int i = stmt.executeUpdate(query);
System.out.println("query" + query);
if(i>0)
{
response.sendRedirect("servletRecord");
}
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
我想使用此程序获取值并将其添加到数据库中,但我不知道存在什么错误。接下来我应该做什么来创建相应的网页来输入值并将其添加到表中?
最佳答案
这将是 HTML。 First learn HTML ,特别是HTML forms .
您想要使用 HTML 表单。创建一个 JSP 文件,该文件应将此 HTML 提供给 Web 浏览器。它看起来像:
<!DOCTYPE html>
<html lang="en">
<head><title>Hello World</title></head>
<body>
<form action="servleturl" method="post">
<p>Empid: <input name="Empid">
<p>Name: <input name="Name">
<p>Age: <input name="Age">
<p>Salary: <input name="Salary">
<p><input type="submit">
</form>
</body>
</html>
您只需更改 form action
值匹配 <url-pattern>
web.xml
中映射的 servlet .
另请参阅:
<小时/>也就是说,与实际问题无关,您的 JDBC 代码对 SQL injection 敏感。 attacks 。使用 PreparedStatement
一路走来。 Prepare here 。那我就不讲连接泄漏风险了。
关于java - 获取输入的方式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3479586/