这是我建立的mydb数据库,新建表username,有两个列值user和pwd
表格内容:
选择File->new->Danamic Web Project
输入项目名称textProject(任意),点击finish,出现下图;
<%@page import="java.util.concurrent.ExecutionException"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.Connection"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
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=ISO-8859-1">
<title>Insert title heretitle>
head>
<body>
<%!
public static final String DBDriver ="org.gjt.mm.mysql.Driver";
public static final String DBUrl="jdbc:mysql://localhost:3306/mydb";
public static final String DBuser="root";
public static final String DBpwd="123456";
%>
<%
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
%>
<%
try{
Class.forName(DBDriver);
conn=DriverManager.getConnection(DBUrl,DBuser,DBpwd);
String sql="select * from username";
ps=conn.prepareStatement(sql);
rs=ps.executeQuery();
%>
<center>
<table>
<tr>
<td>用户名td>
<td>密码td>
tr>
<%
while(rs.next()){
String vuser =rs.getString(1);
String vpwd=rs.getString(2);
%>
<tr>
<td><%= vuser %>td>
<td><%= vpwd %>td>
tr>
<%
}
%>
table>
center>
<%
}catch(Exception e){
System.out.println("数据库连接出现异常!");
}finally{
rs.close();
ps.close();
conn.close();
}
%>
body>
html>
将下载的架包存到合适的地方解压,右键textProject,选择BuildPath,如图,
点击Add External JARS…
找到解压后的如图.jar文件,打开,出现如图:
点击Apply and Close,在项目里出现Referenced Libraries
再将下图中的.jar文件复制到lib文件夹
如图:
将该项目部署到servers里
右键textProject->Run as->Run on Servser
连接成功!