您的位置:首页 > 职场人生

JDBC连接的一个小例子

2009-07-21 09:17 330 查看
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<html>
<head>
<title>My JSP 'seach.jsp' starting page</title>
</head>

<body>
<h2 align="center">学生信息查询</h2>
<form action="studentByName.jsp">
<center>
<p>请输入客户姓名:<input type="text" name="studentName">
<p><input type="submit" value="提交">
<input type="reset" value="重置">
</center>
</form>
</body>
</html>

---------------------------------------------------------------------------------------------------

studentByName.jsp

---------------------------------------------------------------------------------------------------

<%@ page language="java" import="java.util.*,java.sql.*"
pageEncoding="gb2312"%>
<html>
<body>
<%!
public String getString(String str)//中文处理方法
{
if(str==null)
{
str="";
}
else
{
try
{
byte[] b=str.getBytes("ISO-8859-1");
str=new String(b);
}
catch(Exception e)
{
e.printStackTrace();
}
}
return str;
}
%>
<%!
// 定义数据库驱动程序
String DBDRIVER = "com.microsoft.jdbc.sqlserver.SQLServerDriver" ;
// 定义数据库连接地址
String url = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=JWGL" ;
String user="sa";
String password="";

// 定义数据库连接对象,属于java.sql包中的接口
Connection conn = null ;

// 定义Statement对象,用于操作数据库
Statement stmt = null ;

// 定义一字符串变量,用于保存SQL语句
String sql = null ;

// 查询返回的结果集对象
ResultSet rs = null ;
%>
<%
String studentName=request.getParameter("studentName");
if(studentName==null)
{
studentName="";
}
if(studentName.trim().equals(""))//如果输入为空
{
out.println("您的输入有误!请重新输入.");
out.println("<a href='search.jsp'>返回</a>");
}
else
{
studentName=this.getString(studentName);//调用表单中文处理String sql="select * from customer where <%
// 1、加载驱动程序
try
{
Class.forName(DBDRIVER) ;
}
catch(Exception e)
{
// 此处使用out.print是处于演示目的,在实际开发中所有的错误消息,绝对不能够通过out.print打印,否则会存在安全问题
out.println("数据库驱动程序加载失败!!!") ;
}

// 2、连接数据库
try
{
conn = DriverManager.getConnection(url,user,password) ;
}
catch(Exception e)
{
out.println("数据库连接失败!!!") ;
}

// 3、操作数据库
// 通过Connection对象实例化Statement对象
try
{
// 声明结果集可上下移动
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE) ;
// 编写查询的SQL语句
sql = "SELECT * FROM student where student_name="+"'"+studentName+"'" ;
// 查询数据库,此方法返回ResultSet对象
rs = stmt.executeQuery(sql) ;

%>
<table border="1" width="80%">
<tr>
<td>ID</td>
<td>姓名</td>
<td>班级编号</td>
<td>家庭住址</td>
</tr>
<%
while(rs.next())
{
String id = rs.getString(1) ;
String name = rs.getString(2) ;
String classid = rs.getString(5) ;
String addr = rs.getString(7) ;
%>
<tr>
<td><%=id%></td>
<td><%=name%></td>
<td><%=classid%></td>
<td><%=addr%></td>
</tr>
<%
}
%>
</table>
<%
}
catch(Exception e)
{
out.println("操作数据库失败!!!") ;
}
// 4、关闭数据库

try
{
// 关闭结果集
rs.close() ;
// 关闭操作
stmt.close() ;
// 关闭连接
conn.close() ;
}
catch(Exception e)
{
out.println("数据库关闭失败!!!") ;
}
}
%>

</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  职场 休闲 JDBC