1.如果没有安装MySQL,可以通过下面的博客进行下载安装
https://blog.csdn.net/mixika99/article/details/105997881
https://blog.csdn.net/alnorthword/article/details/88034499
2.在eclipse里面连接数据库
https://www.cnblogs.com/caiwenjing/p/8079227.html
上面的博客是在java类文件里面连接数据库,其实也可以在jsp里面连接。
package servlet;import java.sql.*;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.RequestDispatcher;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class Test2 extends HttpServlet{ //jsp连接数据库 private static final long serialVersionUID =1L; public void init(ServletConfig config) throws ServletException{ super.init(config); } public void service(HttpServletRequest request, HttpServletResponse response) throws IOException{ response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); try { Class.forName("com.mysql.jdbc.Driver"); //加载MYSQL JDBC驱动程序 out.println("Success loading Mysql Driver! "); }catch (Exception e) { out.println("Error loading Mysql Driver!"); e.printStackTrace(); } try { Connection connect = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test","root","123456"); //连接URL为 jdbc:mysql//服务器地址/数据库名 ,后面的2个参数分别是登陆用户名和密码 out.println("Success connect Mysql server! "); Statement stmt = connect.createStatement(); ResultSet rs = stmt.executeQuery("select * from user"); //user 为你表的名称 while (rs.next()) { out.println(rs.getString("name")); } }catch (Exception e) { out.println("get data error! "); e.printStackTrace(); } }}
web.xml文件配置
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <servlet> <servlet-name>test2servlet-name> <servlet-class>servlet.Test2servlet-class> servlet> <servlet-mapping> <servlet-name>test2servlet-name> <url-pattern>/test2url-pattern> servlet-mapping> web-app>
运行结果: