Home  >  Article  >  php教程  >  Tutorial on using JSP program to connect to MySQL using JDBC

Tutorial on using JSP program to connect to MySQL using JDBC

高洛峰
高洛峰Original
2016-12-29 17:15:091682browse

Installing and loading the JDBC driver

Put the file mysql-connector-java-5.1.7-bin.jar in the lib file in the project WEB-INF directory, and the installation is complete (The premise is that MySQL has been installed on your machine. If it is not installed, install it first)

Load in the JDBC driver

<%@page language="java" contentType="text/html;charset=gb2312"%>
<!DOCTYPE html>
<html>
  <head>
    <title>加载JDBC驱动程序</title>
  </head>
  <body>
    <%
      try{
        Class.forName("com.mysql.jdbc.Driver");//加载JDBC驱动程序
      }catch(ClassNotFoundException e){
        out.println("找不到驱动类");//抛出异常时,提示信息
      }
    %>
  </body>
</html>

Connect to the MySQL database
Start Mysql and Tomcat,

Use JDBC to connect to the database.

The first way

<%@page language="java" contentType="text/html;charset=gb2312"%>
<%@page import="java.sql.*" %>
<!DOCTYPE html>
<html>
  <head>
    <title>链接MySQL数据库</title>
  </head>
  <body>
    <%
      try{
        Class.forName("com.mysql.jdbc.Driver");//加载JDBC驱动程序
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/javaweb?user=root&password=zhangda890126;;");//链接数据库
          
      }catch(ClassNotFoundException e){
        out.println("找不到驱动类");//抛出异常时,提示信息
      }catch(SQLException e){
        out.println("链接MySQL数据库失败");//处理SQLException异常
      }
    %>
  </body>
</html>

The second way

<%@page language="java" contentType="text/html;charset=gb2312"%>
<%@page import="java.sql.*" %>
<!DOCTYPE html>
<html>
  <head>
    <title>链接MySQL数据库</title>
  </head>
  <body>
    <%
      String url = "jdbc:mysql://localhost:3306/javaweb";//连接数据库的url地址
      String user = "root";//登录数据库的用户名
      String password = "zhangda890126;;";//登录数据库的用户名的密码
      try{
        Class.forName("com.mysql.jdbc.Driver");//加载JDBC驱动程序
        Connection conn = DriverManager.getConnection(url,user,password);//链接数据库
          
      }catch(ClassNotFoundException e){
        out.println("找不到驱动类");//抛出异常时,提示信息
      }catch(SQLException e){
        out.println("链接MySQL数据库失败");//处理SQLException异常
      }
    %>
  </body>
</html>

For more tutorials on how JSP programs use JDBC to connect to MySQL, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn