java 使用JSP将数据插入数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26284330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:38:50  来源:igfitidea点击:

inserting data into database using JSP

javamysqlsqljspservlets

提问by Kriti

I am trying to insert data into my database using following JSP code. I have created database named music and table named tbl_user. After I have entered all the related fields in register.jsp, the control goes to Insertdata.javabut data is not going into database.

我正在尝试使用以下 JSP 代码将数据插入到我的数据库中。我创建了名为 music 的数据库和名为 tbl_user 的表。在我输入 中的所有相关字段后register.jsp,控件会转到Insertdata.java但数据不会进入数据库。

This is my JSP page:

这是我的 JSP 页面:

<!DOCTYPE html>
 <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <!-- Bootstrap core CSS -->
        <link href="assets/css/bootstrap.min.css" rel="stylesheet">

        <!-- Custom styles for this template -->
        <link href="assets/css/signin.css" rel="stylesheet">
        <link href="assets/css/login.css" rel="stylesheet">

        <script src="assets/js/bootstrap.js"></script>
        <title>Sign UP</title>
    </head>
    <body>
        <div class="container">

            <div class="clearfix"></div>
            <div class="col-md-6 col-md-offset-3">
                <div class="panel panel-default login">
                    <div class="panel-heading">Register Here</div>
                    <div class="panel-body">
                        <form class="form-horizontal" role="form" method="post" action="Insertdata">
                            <div class="form-group">
                                <label for="firstname" class="col-sm-3 control-label"> First Name</label>
                                <div class="col-sm-8">
                                    <input type="text" class="form-control" id="firstname"  name="fname" placeholder="First Name">
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="lastname" class="col-sm-3 control-label"> Last Name</label>
                                <div class="col-sm-8">
                                    <input type="text" class="form-control" id="lastname"  name="lname" placeholder="Last Name">
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="adress" class="col-sm-3 control-label">Address</label>
                                <div class="col-sm-8">
                                    <input type="text" class="form-control" id="address"  name="address" placeholder="Address">
                                </div>
                            </div> 
                            <div class="form-group">
                                <label for="inputEmail3" class="col-sm-3 control-label">Email</label>
                                <div class="col-sm-8">
                                    <input type="email" class="form-control" id="inputEmail3"  name="email" placeholder="Email">
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="inputPassword3" class="col-sm-3 control-label">Password</label>
                                <div class="col-sm-8">
                                    <input type="password" class="form-control" id="inputPassword3" name="password" placeholder="Password">
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-sm-offset-3 col-sm-10">
                                    <button type="submit" class="btn btn-default"">Register</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

            </div>     
        </div>
    </body>
</html>

This is my servlet for database connection DatabaseConnection.java

这是我用于数据库连接DatabaseConnection.java 的servlet

package mypackage;

import java.sql.Connection;  
import java.sql.DriverManager;  
import java.sql.ResultSet;  
import java.sql.Statement;  


public class DatabaseConnection {  
Connection conn;  
Statement stmt;  
ResultSet res;  

public DatabaseConnection(){  

}  

public Connection setConnection(){  
try{  
    System.out.println("sdsadasd");  
Class.forName("com.mysql.jdbc.Driver");  
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/music","root","");  
 System.out.println("Connected to the database");  
}catch(Exception e){  

}  
return conn;  
}  

public ResultSet getResult(String sql,Connection conn){  
this.conn=conn;  
try{  
stmt=conn.createStatement();  
res=stmt.executeQuery(sql);  
}catch(Exception e){  

}  
return res;  
}  
}

This is my servlet to insert data Insertdata.java

这是我插入数据的servlet Insertdata.java

package mypackage;

import java.io.IOException;  
import java.io.PrintWriter;  
import java.sql.Connection;  
import java.sql.ResultSet;  
import java.sql.Statement;  
import javax.servlet.RequestDispatcher;  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  


public class Insertdata extends HttpServlet {  

String fname,lname,address,email,password;  
String query;  
Connection conn;  
Statement stmt;  
ResultSet res;  
DatabaseConnection dbconn;  


protected void processRequest(HttpServletRequest request, HttpServletResponse response)  
throws ServletException, IOException {  
response.setContentType("text/html;charset=UTF-8");  
PrintWriter out = response.getWriter();  
try {  

dbconn=new DatabaseConnection();  

//Af_Scheme_Number=request.getParameter("Af_Scheme_Number");  
fname=request.getParameter("fname");  
lname=request.getParameter("lname");  
address=request.getParameter("address");  
email=request.getParameter("email");  
password=request.getParameter("password");  

conn=dbconn.setConnection();  

stmt=conn.createStatement();  
query= "insert into tbl_user(first_name,last_name,address,email,password)"+  
" values('"+fname+"','"+lname+"','"+address+"',"+email+",'"+ password+"')";  
int i=stmt.executeUpdate(query);  

} catch(Exception e){  

    System.out.println("Error");  

}finally {  

out.close();  
}  
}  


@Override  
protected void doGet(HttpServletRequest request, HttpServletResponse response)  
throws ServletException, IOException {  
processRequest(request, response);  
}  


@Override  
protected void doPost(HttpServletRequest request, HttpServletResponse response)  
throws ServletException, IOException {  
processRequest(request, response);  
}  


@Override  
public String getServletInfo() {  
return "Short description";  
}  
}  

回答by Serge Ballesta

Just a vocabulary point : class DatabaseConnectionis not a servlet. But you should read (or read again) a good tutorial on JDBC :

只是一个词汇点:类DatabaseConnection不是 servlet。但是你应该阅读(或再次阅读)关于 JDBC 的一个很好的教程:

  • you do not correctly test the different operations to properly close what you have opened in case of error
  • you do not close what you have opened if things go right
  • you copy parameters from the request in an insert query - google around for SQL injectionto understand whay you should never do that
  • you do not log the result from executeUpdate
  • you hide the exception that can occur but writing "Error" instead of the full stacktrace that could help to understand what happens.
  • 您没有正确测试不同的操作以在出现错误时正确关闭您打开的内容
  • 如果一切顺利,你不会关闭你打开的东西
  • 您从插入查询中的请求中复制参数 - 谷歌搜索SQL 注入以了解您不应该这样做的原因
  • 你不记录结果 executeUpdate
  • 你隐藏了可能发生的异常,但写了“错误”而不是完整的堆栈跟踪,这有助于理解发生了什么。

You should begin by writing a Junit test to control that you can successfully write to database outside of the servlet context. And only when that part works correctly, you integrate the persistence code with into the web application.

您应该首先编写一个 Junit 测试来控制您可以在 servlet 上下文之外成功写入数据库。只有当该部分正常工作时,您才能将持久性代码集成到 Web 应用程序中。

回答by Ajay Kumar Sinha

remove localhost and try 127.0.0.1 ... it worked for me

删除 localhost 并尝试 127.0.0.1 ...它对我有用

conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/music","root","");