jsp连接mysql

<%@ page contentType="text/html" pageEncoding="utf-8"%>
<%@ page import="java.sql.*"%>
<html>
<head>
<title>利用JSP连接数据库并输出表中数据</title>
</head>
<body>
<%!//定义全局变量,其中root代表数据库连接用户名,DBPASS 为密码, mldn 为所连数据库名称
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";//定义DBDRIVER 目的是定义数据库驱动程序
public static final String DBURL = "jdbc:mysql://localhost:3306/mldn";
public static final String DBUSER = "root";
public static final String DBPASS = "kappa.";%>

<%
Connection conn = null;//声明数据库连接对象
PreparedStatement pre = null;//声明数据库操作
ResultSet result = null;//声明数据库结果集
%>

<%
try {
Class.forName(DBDRIVER);//加载驱动程序
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);//取得数据库连接
String sql = "select id,name,job,hiredate,salary from emp";
pre = conn.prepareStatement(sql);//实例化PreparedStatement对象
result = pre.executeQuery();//执行查询操作
%>
<center>
<table border="1" width="80%">
<tr>
<td>id</td>
<td>name</td>
<td>job</td>
<td>hiredate</td>
<td>salary</td>
</tr>
<%
//循环表emp中行的记录
while (result.next()) {
int num = result.getInt(1);
String na = result.getString(2);
String jo = result.getString(3);
String date = result.getString(4);
float sala = result.getFloat(5);
%>
<tr>
<!--循环输出表中信息-->
<td><%=num%></td>
<td><%=na%></td>
<td><%=jo%></td>
<td><%=date%></td>
<td><%=sala%></td>
</tr>

<%
}
%>
</table>
</center>
<%
} catch (Exception e) {
System.out.println(e);
} finally {
result.close();//关闭结果集
pre.close();//关闭连接操作
conn.close();//关闭连接
}
%>
</body>
</html>

jsp连接mysql

上一篇:MySQL数据备份与恢复


下一篇:SqlServer常用语句整理