1 <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
2 <%@ page import="java.sql.*" %>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
7 <title>Insert title here</title>
8 </head>
9 <body>
10 <%
11 PreparedStatement ps = null;
12 Connection ct = null;
13 ResultSet rs = null;
14 String url = "jdbc:sqlserver://localhost:1433;databaseName=test";
15 String user="sa"; //超级管理员
16 String password="sa"; //密码
17 try {
18 //1.加载驱动
19 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
20 System.out.println("加载驱动成功!");
21 }catch(Exception e) {
22 e.printStackTrace();
23 System.out.println("加载驱动失败!");
24 }
25 try {
26 //2.连接
27 ct=DriverManager.getConnection( url,user,password);
28 System.out.println("连接数据库成功!");
29 }catch(Exception e) {
30 e.printStackTrace();
31 System.out.println("连接数据库失败!");
32 }
33
34 /*尝试查询数据库*/
35 try{
36 Statement stmt = ct.createStatement();
37 String sql = "select * from student";
38 // 执行数据库查询语句
39 rs = stmt.executeQuery(sql);
40 while (rs.next()) {
41 String id = rs.getString("SID");
42 String name = rs.getString("SNAME");
43 String age = rs.getString("SSEX");
44
45 out.println("eno:" + id +"\t"+ "ename:" + name +"\t"+"sex:" + age+"<br>");
46 }
47 if (rs != null) {
48 rs.close();
49 rs = null;
50 }
51 if (stmt != null) {
52 stmt.close();
53 stmt = null;
54 }
55 if (ct != null) {
56 ct.close();
57 ct = null;
58 }
59 }
60 catch (SQLException e) {
61 e.printStackTrace();
62 System.out.println("数据库连接失败");
63 }
64
65
66
67 %>
68 </body>
69 </html>