1.在mysql官网下载JDBC驱动程序。
2.把里面的jar包(mysql-connector-java-5.1.41-bin.jar)放进tomcat的安装目录的lib文件夹下,然后重启tomcat。
3..在mysql中创建试验数据,
输入create database student ;创建数据库(student为数据库名)
输入create table stu1 (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(30) DEFAULT NULL,
`sex` varchar(2) DEFAULT NULL,
`birthday` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
4.在eclipse里面创建工程,并创建一个JSP文件,命名为test.jsp,代码如下,就可以打开数据库中存储的内容
<%@ page contentType="text/html; charset=utf-8"
language="java"
import="java.sql.*"
errorPage=""
%>
<%
//驱动程序名
String driverName = "com.mysql.jdbc.Driver";
//数据库用户名
String userName = "root";
//密码
String userPasswd = "123456";
//数据库名
String dbName = "testdb";
//表名
String tableName = "testform";
//联结字符串
String url = "jdbc:mysql://localhost/"
+ dbName + "?user="
+ userName + "&password="
+ userPasswd;
//加载驱动
Class.forName("com.mysql.jdbc.Driver").newInstance();
//建立连接
Connection conn = DriverManager.getConnection(url);
//创建Statement(负责执行sql语句)
Statement stmt = conn.createStatement();
String sql="select * from "
+ tableName;
//获得数据结果集合
ResultSet rs = stmt.executeQuery(sql);
//依次遍历结果集(表中的记录)
while(rs.next())
{
//依据数据库中的字段名打印数据
out.println(rs.getString("name"));
out.println(rs.getString("age"));
}
//关闭连接
rs.close();
stmt.close();
conn.close();
%>