CONEXIÓN SQL SERVER 2008-JSP

12
Sergio Alejandro Prada CONEXIÓN DIRECTA SQL SERVER 2008 – JAVA CONEXIÓN SQL SERVER 2008 A UNA PAGINA WEB JSP Para conectarse existen drivers de 4 tipos, los de tipo 3 y 4 sirven para conectarse directamente. El de tipo 1 viene incluido en las librerías de java y requiere crear DSN de usuario, y configurar el Orígenes de datos (ODBC). Este es el que vamos a utilizar para crear nuestra conexión. Primero que todo debemos crear una base de datos en SQL server 2008

Transcript of CONEXIÓN SQL SERVER 2008-JSP

Page 1: CONEXIÓN SQL SERVER 2008-JSP

Sergio Alejandro Prada

CONEXIÓN DIRECTA SQL SERVER 2008 – JAVA

CONEXIÓN SQL SERVER 2008

A UNA PAGINA WEB JSP

Para conectarse existen drivers de 4 tipos, los de tipo 3 y 4 sirven

para conectarse directamente. El de tipo 1 viene incluido en las

librerías de java y requiere crear DSN de usuario, y configurar el

Orígenes de datos (ODBC).

Este es el que vamos a utilizar para crear nuestra conexión.

Primero que todo debemos crear una base de datos en SQL

server 2008

Page 2: CONEXIÓN SQL SERVER 2008-JSP

Sergio Alejandro Prada

CONEXIÓN DIRECTA SQL SERVER 2008 – JAVA

BASE DE DATOS

CREATE DATABASE Registro

GO

USE Registro

GO

CREATE TABLE Asignatura(

idAsig int IDENTITY (100,1)PRIMARY KEY,

nombre varchar(50),

creditosTeoricos int NOT NULL,

creditosPracticos int NOT NULL,

tipo char(1) NOT NULL,

cuatrimestre int NOT NULL

)

Page 3: CONEXIÓN SQL SERVER 2008-JSP

Sergio Alejandro Prada

CONEXIÓN DIRECTA SQL SERVER 2008 – JAVA

Ahora vamos a crear en origen de datos :

Page 4: CONEXIÓN SQL SERVER 2008-JSP

Sergio Alejandro Prada

CONEXIÓN DIRECTA SQL SERVER 2008 – JAVA

Para agregar un

nuevo origen de datos

damos click en el

botón agregar.

En esta ventana vamos a

seleccionar el driver de SQL

Finalizamos y empezaremos

con el asistente de creación

del nuevo origen de datos.

Page 5: CONEXIÓN SQL SERVER 2008-JSP

Sergio Alejandro Prada

CONEXIÓN DIRECTA SQL SERVER 2008 – JAVA

Ingresamos un

nombre con el

cual

identificaremos

el origen de

datos, una

descripción, y el

nombre del

servidor. Y

damos

siguiente.

Page 6: CONEXIÓN SQL SERVER 2008-JSP

Sergio Alejandro Prada

CONEXIÓN DIRECTA SQL SERVER 2008 – JAVA

Le establecemos nuestra base

de datos al origen de datos.

Y finalizamos el asistente.

Page 7: CONEXIÓN SQL SERVER 2008-JSP

Sergio Alejandro Prada

CONEXIÓN DIRECTA SQL SERVER 2008 – JAVA

Vamos ahora ingresar a netbeans, tenga en cuenta que debe

tener instalado el servidor Apache TomCat. Que el servidor en el

cual se alojara y ejecutara nuestra página web.

Creamos un nuevo proyecto de aplicación web, siguiendo el

asistente.

Page 8: CONEXIÓN SQL SERVER 2008-JSP

Sergio Alejandro Prada

CONEXIÓN DIRECTA SQL SERVER 2008 – JAVA

Page 9: CONEXIÓN SQL SERVER 2008-JSP

Sergio Alejandro Prada

CONEXIÓN DIRECTA SQL SERVER 2008 – JAVA

Page 10: CONEXIÓN SQL SERVER 2008-JSP

Sergio Alejandro Prada

CONEXIÓN DIRECTA SQL SERVER 2008 – JAVA

Código del ejemplo de página JSP: index.jsp

<%--

Document : index

Created on : 2/11/2011, 08:30:14 PM

Author : Zheryio Pc

--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<! DOCTYPE html>

<%@page import= "java.sql.*"%>

<% // Cadena de conexión.

String connectionUrl = "jdbc:odbc:registro";//nombre del orgen de datos

Connection con = null;

Statement stmt = null;

ResultSet rs = null;

try { // Carga el driver sqljdbc

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

}

catch (Exception e)

{ e.printStackTrace();}

%>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>JSP Conexión Directa SQL Server 2008</title>

<style type="text/css">

<!--.Estilo3 {color: #FFFFFF; font-weight: bold;}--></style>

</head>

<body>

<h2 align="center">Tabla Asignatura </h2>

<table width="80%" border="1" align="center" bordercolor="#000000">

<tr bgcolor="#0033CC">

<td> <div align="center" class="Estilo3">idAsig</div></td>

<td><div align="center" class="Estilo3">nombre</div></td>

<td><div align="center" class="Estilo3">creditosTeoricos</div></td>

<td><div align="center" class="Estilo3">creditosPracticos</div></td>

<td><div align="center" class="Estilo3">tipo </div></td>

<td><div align="center" class="Estilo3">cuatrimestre</div></td>

</tr>

Page 11: CONEXIÓN SQL SERVER 2008-JSP

Sergio Alejandro Prada

CONEXIÓN DIRECTA SQL SERVER 2008 – JAVA

<%

try{

con = DriverManager.getConnection(connectionUrl); //Crear y ejecutar una

sentencia SQL que devuelve algunos datos.

String SQL = "SELECT * FROM Asignatura"; //consulta a la base de datos

stmt = con.createStatement();// objeto para el envío de sentencias SQL para la

base de datos.

rs = stmt.executeQuery(SQL); //ejecuta la sentencia de la base de datos

while (rs.next())

{

//carga la tabla de la base de datos

out.print("<tr bordercolor=#000000 bgcolor=#FFFFFF>");

out.print("<td>"+ rs.getString("idAsig") +"</td>");

out.print("<td>"+ rs.getString("nombre") + "</td>");

out.print("<td>"+ rs.getString("creditosTeoricos") + "</td>");

out.print("<td>"+ rs.getString("creditosPracticos") + "</td>");

out.print("<td>"+ rs.getString("tipo") + "</td>");

out.print("<td>"+ rs.getString("cuatrimestre") + "</td>");

out.print("</tr>");

}

}

catch(Exception e)

{

e.printStackTrace();

}

finally {

if (rs != null)

try {rs.close();}

catch(Exception e){}

if (stmt != null)

try { stmt.close(); }

catch(Exception e) {}

if (con != null)

try { con.close(); }

catch(Exception e) {}

}

%>

</body>

</html>

Page 12: CONEXIÓN SQL SERVER 2008-JSP

Sergio Alejandro Prada

CONEXIÓN DIRECTA SQL SERVER 2008 – JAVA

Página web:

SQL server 2008: