JDBC 连接 SQL Server 2005, 2008 数据库

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * JDBC 连接 SQL Server 2005,2008
 * 
 * @author zhanqi
 * 
 */
public class MSSQLSERVER {

    private static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    private static String url = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=Student";

    public static void main(String[] args) {
        Connection ct = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            // 加载驱动类
            Class.forName(driver);
            // 得到连接
            ct = DriverManager.getConnection(url, "root", "root");
            // 得到预编译的 SQL 语句的对象
            ps = ct.prepareStatement("select count(*) from t_student");
            // 得到结果集
            rs = ps.executeQuery();
            // 循环取出记录
            while (rs.next()) {
                System.out.println(rs.getInt(1));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (rs != null) {
                    rs.close();
                }
                if (ps != null) {
                    ps.close();
                }
                if (ct != null) {
                    ct.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

  • Microsoft SQL Server JDBC Driver 3.0 :下载
  • 注:下载,解压后请选择 sqljdbc4.jar

posted on 2011-01-06 07:10  zhanqi  阅读(863)  评论(0编辑  收藏  举报