如何在表中插入并在Apache服务器上显示表内容?

时间:2017-10-17 01:31:18

标签: java mysql

我在MySQL中有数据库 studentdb 和表名学生。我该怎么做才能插入数据并从数据库中获取完整的表。用户名为“ root ”,密码也为“ root ”。

我想在表格中插入数据,之后我想显示表格数据内容。

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class Register extends HttpServlet {

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

        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String pass = request.getParameter("pass");
        try{

        //loading drivers for mysql
        Class.forName("com.mysql.jdbc.Driver");

    //creating connection with the database 
          Connection  con=DriverManager.getConnection
                     ("jdbc:mysql://localhost:3306/studentdb","root","root");

        PreparedStatement ps=con.prepareStatement
                  ("insert into Student values(?,?,?)");

        ps.setString(1, name);
        ps.setString(2, email);
        ps.setString(3, pass);
        int i=ps.executeUpdate();

          if(i>0)
          {
            out.println("You are sucessfully registered");
          }
          String query = "SELECT * FROM student";

      // create the java statement
      Statement st = conn.createStatement();

      // execute the query, and get a java resultset
      ResultSet rs = st.executeQuery(query);

      // iterate through the java resultset
      while (rs.next())
      {
        String name = rs.getString("name");
        String email = rs.getString("email");
        String password = rs.getString("pass");


        // print the results
        System.out.format("%s, %s, %s\n", name, email, password);
      }
      st.close();

        }
        catch(Exception se)
        {
            se.printStackTrace();
        }
        catch (Exception e)
    {
      System.err.println("Got an exception! ");
      System.err.println(e.getMessage());

      }
  }`enter code here`

数据库“name”,“email”,“pass”中有3列。

0 个答案:

没有答案