How to add data to a database using JSP?

In order to add data to a database, you need to use Java code within Java Server Pages (JSP) to perform database operations. Here is a simple example demonstrating how to add data to a database through JSP.

Firstly, import the necessary Java classes and packages in the JSP page, for example:

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

Next, establish a connection to the database and create a `Connection` object.

<%

    Connection conn = null;

    try {

        String url = "jdbc:mysql://localhost:3306/mydatabase"; // 数据库URL

        String username = "root"; // 数据库用户名

        String password = "password"; // 数据库密码

        Class.forName("com.mysql.jdbc.Driver"); // 加载MySQL JDBC驱动程序

        conn = DriverManager.getConnection(url, username, password); // 建立数据库连接

    } catch (Exception e) {

        e.printStackTrace();

    }

%>

Next, write an SQL query to insert data and create a `PreparedStatement` object to execute the query.

<%

    PreparedStatement pstmt = null;

    try {

       String query = "INSERT INTO mytable (column1, column2) VALUES (?, ?)"; // 要插入数据的SQL查询

        pstmt = conn.prepareStatement(query);

        pstmt.setString(1, "value1"); // 设置第一个参数的值

        pstmt.setString(2, "value2"); // 设置第二个参数的值

        pstmt.executeUpdate(); // 执行插入操作

    } catch (Exception e) {

        e.printStackTrace();

    }

%>

Finally, close the database connection and related resources.

<%

    try {

        if (pstmt != null) {

            pstmt.close();

        }

        if (conn != null) {

            conn.close();

        }

    } catch (Exception e) {

        e.printStackTrace();

    }

%>

Please make sure to replace the database URL, username, password, table name, and column names in the sample code with your actual values. Additionally, you should also handle exceptions to provide proper error handling and feedback in case of any errors.

This is a simple example of adding data to a database, which you can modify and expand according to your needs.

bannerAds