关于jsp连接MySQL5.7出现 Access denied for user 'root'@'localhost' (using password: YES)问题(附:数据库查询编码问题)

经过多次尝试:在连接数据库时总是出现这个问题,经过一点点的修改终于解决了这个烦人的问题

不说多直接贴代码

<%@ page contentType="text/html; charset=utf-8" %>   
<%@ page language="java" %>   
<%@ page import="com.mysql.jdbc.Driver" %>   
<%@ page import="java.sql.*" %>   
<%   
//加载驱动程序   
String driverName="com.mysql.cj.jdbc.Driver";   
//数据库信息  
String userName="root";   //数据库用户名
//密码   
String userPasswd="Mysql123";   // 数据库密码
//数据库名   
String dbName="student";   
//表名   
String tableName="stu_info";   
//将数据库信息字符串连接成为一个完整的url(也可以直接写成url,分开写是明了可维护性强)   
 String url="jdbc:mysql://localhost:3306/student?serverTimezone=GMT%2B8"; 
/* String url="jdbc:mysql://localhost:3306/"+dbName+"?user="+userName+"&password="+userPasswd
	+"?serverTimezone=GMT%2B8";   */ 
	try{
		Class.forName("com.mysql.cj.jdbc.Driver").newInstance();   
		Connection conn=DriverManager.getConnection(url, userName, userPasswd);  
		Statement stmt = conn.createStatement();   
		String sql="SELECT * FROM "+tableName;   
		ResultSet rs = stmt.executeQuery(sql);
		out.print("id");   
		out.print("|");   
		out.print("name");   
		out.print("|");   
		out.print("phone");   
		out.print("<br>");   
		while(rs.next()) {   
		out.print(rs.getString(1)+" ");   
		out.print("|");   
		out.print(rs.getString(2)+" ");   
		out.print("|");   
		out.print(rs.getString(3));   
		out.print("<br>");   
		}   
		out.print("<br>");   
		out.print("ok, Database Query Successd!");   
		rs.close();   
		stmt.close();   
		conn.close(); 
	}catch(Exception e){
		out.print(e);
	}
   
  
%>  

(PS:在navicat中新建了数据库student和一张表stu_info如图)

 

 

 

在只是改了把Connection conn=DriverManager.getConnection(url)改成了Connection conn=DriverManager.getConnection(url, userName, userPasswd);就正确了,

 

还是感谢其他两位博主的启发https://www.cnblogs.com/jdbc-mydql/p/JDBC-MySQL.html

https://blog.csdn.net/ph_dream/article/details/80494696

 

附:Java EE连接MySQL不能识别中文

String url="jdbc:mysql://localhost:3306/+"+dbName+"?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8";

(其中dbName是你数据库中的数据库名)

欢迎大家批评指正!!!

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值