📜  Servlet-数据库访问

📅  最后修改于: 2020-11-12 05:42:26             🧑  作者: Mango


本教程假定您已了解JDBC应用程序的工作方式。在开始通过servlet进行数据库访问之前,请确保您具有正确的JDBC环境设置以及数据库。

有关如何使用JDBC及其环境设置访问数据库的更多详细信息,请阅读JDBC教程

首先,让我们创建一个简单的表,并在该表中创建一些记录,如下所示:

建立表格

要在TEST数据库中创建雇员表,请使用以下步骤-

第1步

打开命令提示符,然后更改为安装目录,如下所示:

C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>

第2步

登录数据库如下

C:\Program Files\MySQL\bin>mysql -u root -p
Enter password: ********
mysql>

第三步

TEST数据库中创建表Employee ,如下所示-

mysql> use TEST;
mysql> create table Employees (
   id int not null,
   age int not null,
   first varchar (255),
   last varchar (255)
);
Query OK, 0 rows affected (0.08 sec)
mysql>

创建数据记录

最后,您在Employee表中创建了几条记录,如下所示:

mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
Query OK, 1 row affected (0.05 sec)
 
mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma');
Query OK, 1 row affected (0.00 sec)
 
mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');
Query OK, 1 row affected (0.00 sec)
 
mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');
Query OK, 1 row affected (0.00 sec)
 
mysql>

访问数据库

这是一个示例,显示了如何使用Servlet访问TEST数据库。

// Loading required libraries
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
 
public class DatabaseAccess extends HttpServlet{

   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
   
      // JDBC driver name and database URL
      static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
      static final String DB_URL="jdbc:mysql://localhost/TEST";

      //  Database credentials
      static final String USER = "root";
      static final String PASS = "password";

      // Set response content type
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      String title = "Database Result";
      
      String docType =
         ""-//w3c//dtd html 4.0 " + "transitional//en\">\n";
      
      out.println(docType +
         "\n" +
         "" + title + "\n" +
         "\n" +
         "

" + title + "

\n"); try { // Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); // Open a connection Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); // Execute SQL query Statement stmt = conn.createStatement(); String sql; sql = "SELECT id, first, last, age FROM Employees"; ResultSet rs = stmt.executeQuery(sql); // Extract data from result set while(rs.next()){ //Retrieve by column name int id = rs.getInt("id"); int age = rs.getInt("age"); String first = rs.getString("first"); String last = rs.getString("last"); //Display values out.println("ID: " + id + "
"); out.println(", Age: " + age + "
"); out.println(", First: " + first + "
"); out.println(", Last: " + last + "
"); } out.println(""); // 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(); } finally { //finally block used to close resources try { if(stmt!=null) stmt.close(); } catch(SQLException se2) { } // nothing we can do try { if(conn!=null) conn.close(); } catch(SQLException se) { se.printStackTrace(); } //end finally try } //end try } }

现在让我们在servlet上方进行编译,并在web.xml中创建以下条目

....

   DatabaseAccess
   DatabaseAccess

 

   DatabaseAccess
   /DatabaseAccess

....

现在使用URL http:// localhost:8080 / DatabaseAccess调用此servlet,它将显示以下响应-

Database Result
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal