java链接sqlserver数据库

需要用到sqljdbc.jar包

JSP代码

 1 <%@ page language="java" import="java.sql.*" import="java.io.*" import="java.util.*"  pageEncoding="utf-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title></title>
13     <meta http-equiv="pragma" content="no-cache">
14     <meta http-equiv="cache-control" content="no-cache">
15     <meta http-equiv="expires" content="0">    
16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
17     <meta http-equiv="description" content="This is my page">
18   </head>
19   <%
20 
21         Statement sql;
22         ResultSet rs;
23         String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";   //加载JDBC驱动  
24         String dbURL = "jdbc:sqlserver://172.16.0.5:1433; DatabaseName=Web";   //连接服务器和数据库
25         String userName = "sa";   //用户名  
26         String userPwd = "Htwy*99";   //密码  
27         Connection dbConn;  
28 
29         try {  
30         Class.forName(driverName);  
31         dbConn = DriverManager.getConnection(dbURL, userName, userPwd); 
32         sql=dbConn.createStatement();
33         rs=sql.executeQuery("select*from dbo.StaffBill");
34         System.out.println("Connection Successful!");   //如果连接成功 控制台输出Connection Successful! 
35         
36         out.println("EmployeeID");
37         
38 
39         while(rs.next())
40         {
41         
42         out.println("<br/>");
43         out.println(rs.getString(1));
44 
45         }
46         
47         dbConn.close();
48         } catch (Exception e) {  
49         e.printStackTrace();  
50         }  
51 %>
52   </body>
53 </html>

 

 

posted @ 2017-03-23 11:33  小雨滴答  阅读(363)  评论(0编辑  收藏  举报