JSP program using JDBC connection MySQL tutorial

  • 2021-09-20 21:14:22
  • OfStack

Installing and loading the JDBC driver

Download the JDBC driver mysql-connector-java-5. 1.7. zip
https://www.ofstack.com/softs/214141.html
Place the inside file mysql-connector-java-5. 1.7-bin. jar in the lib file under the project WEB-INF directory, and the installation is complete (provided that your machine already has MySQL installed, if not installed first)

Load EN driver in JDBC


<%@page language="java" contentType="text/html;charset=gb2312"%>
<!DOCTYPE html>
<html>
  <head>
    <title> Loading JDBC Driver </title>
  </head>
  <body>
    <%
      try{
        Class.forName("com.mysql.jdbc.Driver");// Loading JDBC Driver 
      }catch(ClassNotFoundException e){
        out.println(" Driver class not found ");// Prompt information when an exception is thrown 
      }
    %>
  </body>
</html>

Connect to MySQL database
Start Mysql and Tomcat,

Connect to the database using JDBC.

Mode 1


<%@page language="java" contentType="text/html;charset=gb2312"%>
<%@page import="java.sql.*" %>
<!DOCTYPE html>
<html>
  <head>
    <title> Link MySQL Database </title>
  </head>
  <body>
    <%
      try{
        Class.forName("com.mysql.jdbc.Driver");// Loading JDBC Driver 
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/javaweb?user=root&password=zhangda890126;;");// Linked database 
         
      }catch(ClassNotFoundException e){
        out.println(" Driver class not found ");// Prompt information when an exception is thrown 
      }catch(SQLException e){
        out.println(" Link MySQL Database failure ");// Deal with SQLException Anomaly 
      }
    %>
  </body>
</html>

Mode 2


<%@page language="java" contentType="text/html;charset=gb2312"%>
<%@page import="java.sql.*" %>
<!DOCTYPE html>
<html>
  <head>
    <title> Link MySQL Database </title>
  </head>
  <body>
    <%
      String url = "jdbc:mysql://localhost:3306/javaweb";// Connecting to the database url Address 
      String user = "root";// User name for logging in to the database 
      String password = "zhangda890126;;";// Password for the user name that logs in to the database 
      try{
        Class.forName("com.mysql.jdbc.Driver");// Loading JDBC Driver 
        Connection conn = DriverManager.getConnection(url,user,password);// Linked database 
         
      }catch(ClassNotFoundException e){
        out.println(" Driver class not found ");// Prompt information when an exception is thrown 
      }catch(SQLException e){
        out.println(" Link MySQL Database failure ");// Deal with SQLException Anomaly 
      }
    %>
  </body>
</html>


Related articles: