建立web程序JSPSQL,加入JSP文件SqlJsp.jsp->build path 加入reference库。或是加入web-ifn的lib中,不要重复否则无法解析
其次在import java.sql.*。注册tomcat
运行http://localhost:8080/JSPSQL/SqlJsp.jsp
<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'SqlJsp.jsp' starting page</title>
<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 server="localhost"; //MYSQL 服务器的地址
String dbname="first"; //MYSQL 数据库的名字
String user="root"; //MYSQL 数据库的登录用户名
String pass="5106"; //MYSQL 数据库的登录密码
String port="3306"; //SQL Server 服务器的端口号,默认为1433
//数据库连接字符串
String url ="jdbc:mysql://"+server+":"+port+"/"+dbname+"?user="+user+"&password="+pass+"&useUnicode=true&characterEncoding=GB2312";
//加载驱动程序
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
//建立连接
Connection conn= DriverManager.getConnection(url);
//创建语句对象
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
// **** 数据库连接代码 结束 *******
String sql="select * from about";
ResultSet rs=stmt.executeQuery(sql);
//rs.first();
while(rs.next()){
out.print("ID:");
out.print(rs.getString("id")+" name:");
out.println(rs.getString("name")+"<br>");
}
rs.close();
stmt.close();
conn.close();
%>
This is my JSP page. <br>
</body>
</html>