SQLServer连接语句

本文提供了一个使用Java连接Microsoft SQL Server数据库并执行简单查询的示例代码。该示例展示了如何加载驱动、建立连接、执行SQL语句及处理结果集。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class SqlServerTest {

    //驱动类

    staticString driverClass=

       "com.microsoft.jdbc.sqlserver.SQLServerDriver";

    //连接字符串

    staticString url=

       "jdbc:microsoft:sqlserver://127.0.0.1:1433;dataBaseName=Test";

    //密码

    staticString password= "peter";

     // 用户名

    staticString username= "peter";

    //待执行的 SQL 语句

    staticString sql= "SELECT * FROM Test";

 

    publicstatic voidmain(String[] args) {

       Connection conn = null ;

       PreparedStatement pstmt =null ;

       ResultSet rs = null;

 

       try{

           Class.forName(driverClass );

           conn = DriverManager.getConnection(url , username , password );

           pstmt = conn.prepareStatement(sql );

           rs = pstmt.executeQuery();

           while(rs.next()) {

              System. out.println( "OK.");

           }

           System. out.println( "OK too.");

           rs.close();

           pstmt.close();

           conn.close();

       } catch(ClassNotFoundException e) {

           System. out.println( "驱动类没有找到 ." );

           e.printStackTrace();

       } catch(SQLException e) {

           e.printStackTrace();

       } finally{

           if(rs != null) //结果集没有关闭时关闭结果集

              try{

                  rs.close();

              } catch(SQLException e) {

                  e.printStackTrace();

              }

           if(pstmt != null) //发送对象没有关闭时关闭发送对象

              try{

                  pstmt.close();

              } catch(SQLException e) {

                  e.printStackTrace();

              }

           if(conn != null//连接没有关闭时关闭连接

              try{

                  conn.close();

              } catch(SQLException e) {

                  e.printStackTrace();

              }

       }

 

    }

}


that well does capture Exception program .


原地址:http://www.blogjava.net/lpeter/archive/2006/12/22/89501.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值