使用Microsoft SQL Server 2005 JDBC Driver联接数据库的例子

11:01上午 四月 17, 2008 in category 工作 by 肖俊峰

别忘了把sqljdbc.jar放在Tomcat的CLASSPATH路径中,例如在Tomcat5.5下,要放在common\lib下。

<%@ page contentType="text/html; charset=GBK" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.text.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="javax.sql.*" %>
<%@ page import="javax.naming.*" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<link href="css/common.css" rel="stylesheet" type="text/css" >
<title>测试页面</title>
</head>
<body>
<%request.setCharacterEncoding("GBK");%>

<%

    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    Connection conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=Northwind;user=sa;password=xjfdlj;");
    Statement stmt = null;
    ResultSet rs = null;

    try {
            stmt = conn.createStatement();
            rs = stmt.executeQuery("select * from Customers");
            while(rs.next()){
%>
<%=rs.getString("CustomerID")%><br>
<%
            }
            rs.close();rs=null;
            stmt.close();stmt = null;
            conn.close();conn = null;
    } finally {
            if (rs != null) {
                    try {
                            rs.close();
                    } catch (Exception sqlex) {
                    }
                    rs = null;
            }
            if (stmt != null) {
                    try {
                            stmt.close();
                    } catch (Exception sqlex) {
                    }
                    stmt = null;
            }
            if (conn != null) {
                    try {
                            conn.close();
                    } catch (Exception sqlex) {
                    }
                    conn = null;
            }
    }
%>


</body>

</html>

评论[0]

评论:

发表一条评论:
  • HTML语法: 启用