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"%>加载JDBC驱动程序 <% try{ Class.forName("com.mysql.jdbc.Driver");//加载JDBC驱动程序 }catch(ClassNotFoundException e){ out.println("找不到驱动类");//抛出异常时,提示信息 } %>
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.*" %>链接MySQL数据库 <% 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异常 } %>
The second way
<%@page language="java" contentType="text/html;charset=gb2312"%> <%@page import="java.sql.*" %>链接MySQL数据库 <% 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异常 } %>
For more tutorials on how JSP programs use JDBC to connect to MySQL, please pay attention to the PHP Chinese website!