SQLServer连接语句
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |