jsp连接MySQL数据库
1、打开eclipse,菜单栏下,File-new,打开Dynamic Web Project,创建一个jsp project,为方便起见,本文直接在jsp页面里写java代码进行数据库的连接。代码如下图。大部分网友应该都可以看懂这段代码的涵义,这里就不赘述了。
其中需要注意的是 String url="jdbc:mysql://localhost:3306/mydb" 其中的3306是MySQL安装时的端口号,默认的是3306,如果你安装MySQL时更改了端口号就要在这里填写你更改的端口号。下面是我的jsp文档
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="java.sql.Connection" %>
<%@page import="java.sql.*" %>
<%@page import="java.sql.DriverManager;" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<table border="1" align="center">
<tr>
<td>书名</td>
<td>作者</td>
</tr>
<%
String driverClass="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/mydb";
String user="root";
String password="1234";
String a="zhangsan";
Connection conn;
try{
Class.forName(driverClass);
conn=DriverManager.getConnection(url,user,password);
Statement stmt=conn.createStatement();
String sql="select * from books";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()){
%>
<tr>
<td><%=rs.getString("bookname") %></td>
<td><%=rs.getString("writer") %></td>
</tr>
<%
}
}
catch(Exception ex){
ex.printStackTrace();
}
%>
</table>
</body>
</html>


2、然后在这个project的WebContent\WEB-INF\lib的文件夹里添加之前提到的连接驱动 mysql-connector-java-3.1.14-bin.jar,将其复制到lib的文件夹中。保存项目,然后运行,就会在网页中出现表格。

3、是不是很简单呢,希望这篇经验能够给大家带来方便。