今日安装配置了MySQL,学习了利用MySQL可视化工作台建数据库与表,学习了jsp与数据库的连接。
遇到了MySQL版本与适配器版本不对应的问题,以下是结果图与测试代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>
<html>
<head>
<title>通过JSP打开数据表</title>
</head>
<body>
<%
try {
Class.forName("com.mysql.jdbc.Driver"); //驱动程序名
String url = "jdbc:mysql://localhost:3306/classname"; //数据库名
String username = "root"; //数据库用户名
String password = "123456"; //数据库用户密码
Connection conn = DriverManager.getConnection(url, username, password); //连接状态
if(conn != null){
out.print("数据库连接成功!");
out.print("<br />");
Statement stmt = null;
ResultSet rs = null;
String sql = "SELECT *FROM classdomo;"; //查询语句
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
out.print("查询结果:");
out.print("<br />");
out.println("课程"+" "+"教师"+" "+"地点");
out.print("<br />");
while (rs.next()) {
out.println(rs.getString("class")+"   "+rs.getString("teacher")+"   "+rs.getString("address")); //将查询结果输出
}
}
else{
out.print("连接失败!");
}
}catch (Exception e) {
out.print("数据库连接异常!");
}
%>
</body>
</html>