JSP如何连接SQL SERVER,请写个示例

public class UseExecuteQuery{
 /**
  * @param args
  */
 public static void main(String[] args) {
  String url=”jdbc:microsoft:sqlserver://localhost:1433;DataBaseName=jsp_test”;
  String userName=”sa”;
  String password=”";
  String sql=null;
  Connection conn=null;
  Statement stmt=null;
  try{
   //第一步:加载驱动器
   Class.forName(”com.microsoft.jdbc.sqlserver.SQLServerDriver”);
                     System.out.println(”加载成功”);
  }
  catch(ClassNotFoundException e){
   System.out.print(”ClassNotFoundException”);
   System.out.print(”加载驱动器类时出现异常”);
  }
  try{
   //第二步:调用DriverManager.getConnection 静态方法得到数据库连接
   conn=DriverManager.getConnection(url,userName,password);
   System.out.println(”连接成功”);
   //创建statement
   stmt=conn.createStatement();
    sql=”select * from student where stu_id='12′”;
   //sql=”INSERT INTO student(stu_id,name,address,birthdate,age)”+”VALUES('12′,'zhangjun','shanghai','1984/07/01′,'23′)”;
    //stmt.executeUpdate(”delete from student where stu_id='12′”);
          ResultSet rs=stmt.executeQuery(sql);
    //System.out.println(”Insert a row successful”);
        while(rs.next()){
           String id=rs.getString(1);
           String name=rs.getString(2);
           String address=rs.getString(3);
           System.out.println(id+”  “+name+”  “+address);
          }
          rs.close();
          stmt.close();
   
  }
  catch(SQLException e){
   System.out.println(e.getMessage());
   System.out.println(”出现sqlException 异常”);
  }
  finally{
   try{
                 System.out.println(”关闭数据库的连接”);
    //关闭语句和数据库连接
    //stmt.close();
                if(conn!=null)
    conn.close();
   }
   catch(SQLException e){
    System.out.println(”Close SQLException”);
    System.out.println(”关闭数据库连接时出现异常”);
   }
  }
 }
}
数据库连接也可通过连接池。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值