JSP连接SQLserver数据库

1.引入外部jar包

JSP连接SQLserver数据库_第1张图片

2.编写jsp页面

<%@ page language="java" contentType="text/html; charset=utf-8"   pageEncoding="utf-8"%>
<%@ page  import="java.sql.*" %>




Insert title here


<%
    PreparedStatement ps = null;
    Connection ct = null;
    ResultSet rs = null;

    String url = "jdbc:sqlserver://localhost:1433;databaseName=test";
    String user="sa";  //超级管理员
    String password="***********";  //密码

    try {
        //1.加载驱动
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        System.out.println("加载驱动成功!");
    }catch(Exception e) {
        e.printStackTrace();
        System.out.println("加载驱动失败!");
    }
    try {  
        //2.连接
        ct=DriverManager.getConnection( url,user,password);
        System.out.println("连接数据库成功!");
    }catch(Exception e) {
        e.printStackTrace();
        System.out.println("连接数据库失败!");
    }
    
    
    
    out.println("select * from emp"+"
"); /*尝试查询数据库*/ try{ Statement stmt = ct.createStatement(); String sql = "select * from emp"; // 执行数据库查询语句 rs = stmt.executeQuery(sql); while (rs.next()) { String id = rs.getString("eno"); String name = rs.getString("ename"); String age = rs.getString("sex"); out.println("eno:" + id +"\t"+ "ename:" + name +"\t"+"sex:" + age+"
"); } if (rs != null) { rs.close(); rs = null; } if (stmt != null) { stmt.close(); stmt = null; } if (ct != null) { ct.close(); ct = null; } } catch (SQLException e) { e.printStackTrace(); System.out.println("数据库连接失败"); } %>

3.运行

JSP连接SQLserver数据库_第2张图片

你可能感兴趣的:(JavaWeb,javaWeb由浅入深)