您现在的位置是:网站首页> 编程资料编程资料

JSP程序使用JDBC连接MySQL的教程_JSP编程_

2023-05-25 127人已围观

简介 JSP程序使用JDBC连接MySQL的教程_JSP编程_

安装和加载JDBC驱动程序

下载JDBC驱动程序mysql-connector-java-5.1.7.zip
https://www.jb51.net/softs/214141.html
将里面的文件mysql-connector-java-5.1.7-bin.jar放在项目WEB-INF目录下的lib文件中,安装就已经完成了(前提是你的机器已经安装了MySQL,如果没有安装先安装)

加载在JDBC驱动程序

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

连接MySQL数据库
启动Mysql和Tomcat,

使用JDBC连接数据库。

第一种方式

<%@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异常 } %>

第二种方式

<%@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异常 } %>

-六神源码网