首先建立web项目
File->New->Dynamic Web Project
自己取个项目名字,尽量不要用中文,然后finish
导入jar包,要和自己的mysql版本对应。我的是Mysql 8.0
把下载的jar包放在项目的WebContent->WEB-INF->lib
目录下。
在Mysql数据库中创建一个student数据库,在此数据库中创建student表,sno和sname两个属性就够了。
在WebContent目录下新建 testMysql.jsp文件
<%@page contentType="text/html; charset=UTF-8"
import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
从mysql数据库中读取的数据:
<hr>
<table border=1>
<tr><th>学号</th><th>姓名</th></tr>
<%
String driverName="com.mysql.cj.jdbc.Driver";
String userName="root";
String userPasswd="20190225";
String dbName="student";
String tableName="student"; //注意时区问题
String url="jdbc:mysql://localhost:3306/"+dbName+"?&serverTimezone=GMT%2B8";
Connection con=null; Statement s; ResultSet rs;
try
{ //注册驱动 jdbc中oooooooo
Class.forName(driverName).getDeclaredConstructor().newInstance();
}
catch(ClassNotFoundException e)
{
System.out.print("Error loading Driver,不能加载驱动程序!");}
try
{ //获取连接
con=DriverManager.getConnection(url,userName,userPasswd);
}
catch(SQLException er)
{
System.out.print("Error getConnection,不能连接数据库!");}
try
{
s=con.createStatement(); //Connection类与指定数据库连接
String sql="SELECT*FROM "+tableName;//查询语句
rs=s.executeQuery(sql);//执行
while(rs.next())//处理查询结果
{
out.println("<tr>");
out.println("<td>"+rs.getString("sno")+"</td>");
out.println("<td>"+rs.getString("sname")+"</td>");
out.println("</tr>");
}
rs.close();s.close();con.close();//释放资源
}
catch(SQLException er)
{System.err.println("Error executeQuery,不能执行检查!");
}
%>
</table>
</body>
</html>
执行结果