数据库连接总会出现各种意想不到的bug,所以在这里详细说明一下jsp连接数据库的操作,希望能帮到各位。
2.安装mysql,在选择安装类型上选择Custom,在Devoloper Components上选择This feature,and all subfeatures,will be installed on local hard drive,可以选择安装路径,也可以选择默认路径,之后一直点击next即可完成安装,但是一定记住设置的访问数据库的密码,用户名一般为root。
4.安装Navicat,一直点击下一步即可,安装完成后,打开Navicat,点击连接
然后输入连接名和密码,点击确定即可,然后就可以里面建立数据库了。
5.jsp连接数
<%@page import="java.sql.SQLException"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.*"%>
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
String url = "jdbc:mysql://localhost:3307/test";//注意我这里是3307是因为我的端口号设置为3307,默认为3306,test是你的数据库名字,如果你用的是mysql8.0版本,需要在后面加入?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT,即url=“jdbc:mysql://localhost:3307/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT”
String userName = "root";
String password = "password";
Connection conn = null;
try{
Class.forName("com.mysql.jdbc.Driver");
out.print("tyet");
}catch(ClassNotFoundException e){
out.print("加载驱动异常");
}
try {
conn = DriverManager.getConnection(url,"root","password");
}catch(SQLException e){
out.print("连接数据库异常");
}
if(conn == null) {
out.print("连接数据库失败");
} else{
out.print("连接成功");
}
try{
conn.close();
}catch(SQLException e){
out.print("数据库关闭异常!");
}
%>
</body>
</html>
运行成功截图
因篇幅问题不能全部显示,请点此查看更多更全内容