Elipse web项目连接MySQL数据库

1 篇文章 0 订阅

首先建立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>

执行结果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值