JSP | 使用纯JAVA驱动连接MySQL数据库

本程序采用的集成开发环境是eclipse。

采用的数据库是JspStudy里集成的MySQL数据库。

MySQL的java连接驱动在jspstudy的安装目录下Tomcat——>lib文件夹下:


没有安装jspstudy的话,mysql的java驱动可以在官网下载:https://dev.mysql.com/downloads/connector/

本程序使用eclipse布置web工程时,需要将此驱动布置在webcontent——>WEB-INF——>lib目录下。

这是mysql数据库里进行测试的数据库text下的users表,接下来对其进行来连接测试。


测试程序:

<%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK"%>
<%@ page import="java.sql.*"%>
<html>
<head>
<title>useMySQL.jsp</title>
</head>
<body bgcolor="lightblue">
	<%
		Connection con = null;
		Statement st = null;
		ResultSet rs = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
			st=con.createStatement();
			rs=st.executeQuery("select * from users");
			out.print("<table border=1>");
			out.print("<tr>");
				out.print("<th>id</th>");
				out.print("<th>username</th>");
				out.print("<th>password</th>");
				out.print("<th>name</th>");
			out.print("</tr>");
			while(rs.next()){
				out.print("<tr>");
					out.print("<td>"+rs.getString(1)+"</td>");
					out.print("<td>"+rs.getString(2)+"</td>");
					out.print("<td>"+rs.getString(3)+"</td>");
					out.print("<td>"+rs.getString(4)+"</td>");
				out.print("</tr>");
			}
			out.print("</table>");
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try{
				if(rs!=null){
					rs.close();
				}
				if(st!=null){
					st.close();
				}
				if(con!=null){
					con.close();
				}
			}catch (SQLException e) {
				e.printStackTrace();
			}
		}
	%>
</body>
</html> 

测试结果如下:


猜你喜欢

转载自blog.csdn.net/ZYZMZM_/article/details/80246781