1. 程式人生 > >sql server數據庫數據查詢成功

sql server數據庫數據查詢成功

pan 超級 dstat col lan con print ring dtd

 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>

sql server數據庫數據查詢成功