How to connect MySQL database in JSP?

To connect a MySQL database in JSP, you need to follow these steps:

Import the necessary JDBC driver (e.g. `mysql-connector-java`).

   <%@ page import="java.sql.*" %>

Define database connection parameters in the JSP page, including URL, username, and password.

   String url = "jdbc:mysql://localhost:3306/mydb";

   String username = "root";

   String password = "password";

Create a database connection object in the JSP page and establish a connection with the database.

   Connection connection = null;

   try {

       Class.forName("com.mysql.jdbc.Driver");

       connection = DriverManager.getConnection(url, username, password);

   } catch (Exception e) {

       e.printStackTrace();

   }

Use the connection object to execute SQL queries or updates.

   try {

       Statement statement = connection.createStatement();

       ResultSet resultSet = statement.executeQuery("SELECT * FROM mytable");

       // 处理结果集...

       statement.close();

   } catch (SQLException e) {

       e.printStackTrace();

   }

After completing all database operations, close the database connection.

   try {

       if (connection != null) {

           connection.close();

       }

   } catch (SQLException e) {

       e.printStackTrace();

   }

Please note that placing database-related code directly in JSP pages is not a best practice. A better approach is to encapsulate the database interaction logic in a Java class, and then call the methods of this class in the JSP page to handle database operations. This can improve code maintainability and reusability.

bannerAds