Apéndice C: Código Fuente del Programa DBConnection.java



Similar documents
JDBC. It is connected by the Native Module of dependent form of h/w like.dll or.so. ex) OCI driver for local connection to Oracle

Database Programming. Week *Some of the slides in this lecture are created by Prof. Ian Horrocks from University of Oxford

Chapter 9 Java and SQL. Wang Yang wyang@njnet.edu.cn

What is ODBC? Database Connectivity ODBC, JDBC and SQLJ. ODBC Architecture. More on ODBC. JDBC vs ODBC. What is JDBC?

CS/CE 2336 Computer Science II

Database Access from a Programming Language: Database Access from a Programming Language

Database Access from a Programming Language:

CHAPTER 3. Relational Database Management System: Oracle. 3.1 COMPANY Database

COSC344 Database Theory and Applications. Java and SQL. Lecture 12

Java and Databases. COMP514 Distributed Information Systems. Java Database Connectivity. Standards and utilities. Java and Databases

CS 377 Database Systems SQL Programming. Li Xiong Department of Mathematics and Computer Science Emory University

Brazil + JDBC Juin 2001, douin@cnam.fr

The JAVA Way: JDBC and SQLJ

Security Module: SQL Injection

JDBC (Java / SQL Programming) CS 377: Database Systems

Schema XML_PGE.xsd. element GrupoInformes. attribute XML_PGE.xsd unqualified qualified

Matisse Java Programmer s Guide

Dictionary (catálogo)

LSINF1124 Projet de programmation

Supplement IV.C: Tutorial for Oracle. For Introduction to Java Programming By Y. Daniel Liang

SQL and Java. Database Systems Lecture 19 Natasha Alechina

Database System Concepts

Evaluation. Copy. Evaluation Copy. Chapter 7: Using JDBC with Spring. 1) A Simpler Approach ) The JdbcTemplate. Class...

Propiedades del esquema del Documento XML de envío:

Java DataBase Connectivity (JDBC)

Services. Relational. Databases & JDBC. Today. Relational. Databases SQL JDBC. Next Time. Services. Relational. Databases & JDBC. Today.

1 SQL Data Types and Schemas

Supplement IV.D: Tutorial for MS Access. For Introduction to Java Programming By Y. Daniel Liang

How To Use The Database In Jdbc.Com On A Microsoft Gdbdns.Com (Amd64) On A Pcode (Amd32) On An Ubuntu (Amd66) On Microsoft

Chapter 4: SQL. Schema Used in Examples

Java Server Pages and Java Beans

EE 1130 Freshman Eng. Design for Electrical and Computer Eng.

DIPLOMADO DE JAVA - OCA

public class demo1swing extends JFrame implements ActionListener{

Prof. Edwar Saliba Júnior

Why Is This Important? Database Application Development. SQL in Application Code. Overview. SQL in Application Code (Contd.

Problem 1 (1.5 points)

NGASI AppServer Manager SaaS/ASP Hosting Automation for Cloud Computing Administrator and User Guide

Part IV: Java Database Programming

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Sales Management Main Features

COMPUTACIÓN ORIENTADA A SERVICIOS (PRÁCTICA) Dr. Mauricio Arroqui EXA-UNICEN

Altas, Bajas y Modificaciones de Registros en tabla MYSQL

Overview. Database Application Development. SQL in Application Code (Contd.) SQL in Application Code. Embedded SQL. Embedded SQL: Variables

Introduction to Java. Module 12: Networking (Java Sockets) Prepared by Costantinos Costa for EPL 233. ΕΠΛ233 Αντικειμενοστρεφής Προγραμματισμός 1

Division of Informatics, University of Edinburgh

ECCAIRS 5 Instalación

Estructura de aplicación en PHP para System i

Tema 7 GOING TO. Subject+ to be + ( going to ) + (verb) + (object )+ ( place ) + ( time ) Pronoun

RISC Processor Simulator (SRC) INEL 4215: Computer Architecture and Organization September 22, 2004

Bucle for_in. Sintaxis: Bucles for_in con listas. def assessment(grade_list): """ Computes the average of a list of grades

!"# $ %!&' # &! ())*!$

Security Code Review- Identifying Web Vulnerabilities

OMEGA SOFT WF RISKEVAL

TP1 : Correction. Rappels : Stream, Thread et Socket TCP

Mail User Agent Project

Trabajo Fin de Grado

Working With Derby. Version 10.2 Derby Document build: December 11, 2006, 7:06:09 AM (PST)

Course Intro Instructor Intro Java Intro, Continued

Lesson: All About Sockets

Database Application Development. Overview. SQL in Application Code. Chapter 6

Advanced Network Programming Lab using Java. Angelos Stavrou

Introducción a las bases de datos SQL Libro de referencia

To create a universal SQL client for accessing local or remote database ( 35.2). To execute SQL statements in a batch mode ( 35.3).

Tema: Encriptación por Transposición

Using Netbeans and the Derby Database for Projects Contents

CS2506 Operating Systems II Lab 8, 8 th Tue/03 /2011 Java API

AV-002: Professional Web Component Development with Java

New Server Installation. Revisión: 13/10/2014

Ranking de Universidades de Grupo of Eight (Go8)

Discover Natural Science for ESO 1 and 2

INTELIGENCIA DE NEGOCIO CON SQL SERVER

TDD da un capo all altro. Matteo Vaccari (cc) Alcuni diritti riservati

Visión general de la integración con asanetwork

learning science through inquiry in primary classroom Overview of workshop

Programa llamado insert.html

Java Programming. JDBC Spring Framework Web Services

Computer Security - Tutorial Sheet 3: Network & Programming Security

Web Application Development on a Linux System With a DB2 Database By Alan Andrea

TP : Système de messagerie - Fichiers properties - PrepareStatement

Application Development A Cocktail of Java and MCP. MCP Guru Series Dan Meyer & Pramod Nair

CS506 Web Design and Development Solved Online Quiz No. 01

Copyright TeachMe.com 242ea 1

Práctica 1: PL 1a: Entorno de programación MathWorks: Simulink

Spanish Grammar II. Tierra Encantada Charter School. Contact Number: (505)

Chapter 2 Introduction to Java programming

Ejercicios propuestos C. Alexander IV.2 Parametric VaR

Socket Programming in Java

Assignment 4 Solutions

ENVIRONMENT: Collaborative Learning Environment

WRITING DATA TO A BINARY FILE

Application for Admission School Year

Transcription:

Apéndice C: Código Fuente del Programa DBConnection.java import java.sql.*; import java.io.*; import java.*; import java.util.*; import java.net.*; public class DBConnection Connection pgsqlconn = null; /*Variable para la conexión a Postgres*/ Connection connection = null; /*Variable para la conexión a Mysql */ public void connection() Statement stmt=null; ResultSet rset=null; try /*Conexión a la base de datos de Postgres*/ Class.forName("org.postgresql.Driver"); String pgsqlurl = "jdbc:postgresql://localhost:5432/isystemdb"; String pgsqluser = "test"; String pgsqlpw = "test"; pgsqlconn = DriverManager.getConnection(pgsqlURL, pgsqluser, pgsqlpw); /*Conexión a la base de datos de Mysql*/ Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://localhost:3306/isystemdb"; String username = "root"; String password = "saviaga"; connection = DriverManager.getConnection(url, username, password); /*Obtenemos la información de las tablas de Postgres*/ stmt = pgsqlconn.createstatement (); rset = stmt.executequery ("select * from pg_tables"); /*Mandamos esa información a la función guarda_info(resultset,connection)*/ guarda_info(rset,pgsqlconn); /*Cerramos las conexiones*/ pgsqlconn.close(); connection.close(); //fin del try catch (ClassNotFoundException cnfe) System.out.println("Could not load database driver:" + cnfe.getmessage());

catch (SQLException sqle) System.out.println("Could not connect to the database: " + sqle.getmessage()); //Fin de connection() /************************************************************************************ * guarda_info recibe el resultado del query select * from pg_tables * * dicho query lo recibe en 'rset', rset contiene una tabla * * con todos los nombres de las tablas entre otras caracteristicas(schemaname tablename tableowner) * ************************************************************************************/ public void guarda_info(resultset rset,connection conn) try Statement stmt2 =null; int cont=0; char x = 'p'; char y = 'g'; char z ='_'; String nombretabla= ""; ResultSet rset2 =null; stmt2 = conn.createstatement (); while (rset.next ()) try /*Obtiene el nombre de una tabla*/ nombretabla =rset.getstring(2); if (((nombretabla.charat(0)==x) (nombretabla.charat(1)==y)) &&(nombretabla.charat(2)==z)) System.out.println("\n Las tablas que no nos interesan son: "+ nombretabla ); /*Hacemos un Select * from <tabla actual>*/ rset2 = stmt2.executequery ("select * from " + rset.getstring(2)); /*La información obtenida del query anterior la mandamos a guarda_col(resultset,string) junto con el nombre de la tabla*/ guarda_col(rset2,rset.getstring(2)); stmt2.close(); cont++; catch (Exception e) System.out.println( e.tostring() ); catch (SQLException sqle) System.out.println("Could not connect to the database(3): " + sqle.getmessage());

//fin de la clase guarda_info(resultset,connection) /*********************************************************************************** * Recibe el resultado de query en rset (select * from <tabla actual> * *junto el nombre de las tablas y dos archivos de texto * ***********************************************************************************/ public void guarda_col(resultset rset, String nombre_tabla) String columnname,query,type,type2=""; int numberofcolumns, numberofcolumns2=0; ResultSetMetaData metadata,metadata2= null; char a = 'p'; char b = 'g'; char c ='_'; try rset.beforefirst(); metadata= rset.getmetadata(); numberofcolumns = metadata.getcolumncount(); /*Ahora comenzamos a construir el query que utilizaremos para introducir los datos en la tabla de Mysql */ query = "insert into " + nombre_tabla + "("; for ( int i=1;i<=numberofcolumns;i++) columnname = metadata.getcolumnlabel(i); type = metadata.getcolumntypename(i); query+= columnname + ","; query=query.substring(0,query.length()-1)+ ") values ("; for ( int x=1; x<=numberofcolumns;x++) query+="?,"; query=query.substring(0,query.length()-1)+ ")"; if (((nombre_tabla.charat(0)==a) (nombre_tabla.charat(1)==b))&&(nombre_tabla.charat(2)==c)) System.out.println("\n Estas tablas no nos interesan"+ nombre_tabla); PreparedStatement pstmt = connection.preparestatement(query); while (rset.next()) try metadata2= rset.getmetadata(); numberofcolumns2 = metadata2.getcolumncount(); for ( int z=1;z<=numberofcolumns2;z++) type2 = metadata2.getcolumntypename(z); /*Checa que tipo de dato es para meterlo en el query*/ If ((type2.compareto("name")==0) (type2.compareto("varchar")==0) (type2.compareto("char")==0)) pstmt.setstring(z,rset.getstring(z));

if ((type2.compareto("int4")==0) (type2.compareto("int8")==0) (type2.compareto("numeric")==0)) pstmt.setlong(z,rset.getlong(z)); if (type2.compareto("bool")==0) pstmt.setboolean(z,rset.getboolean(z)); if ((type2.compareto("text")==0) (type2.compareto("_text")==0) (type2.compareto("anyarray")==0)) pstmt.setstring(z,rset.getstring(z)); if (type2.compareto("abstime")==0) pstmt.settime(z,rset.gettime(z)); if ((type2.compareto("float4")==0) (type2.compareto("_float4")==0) (type2.compareto("float8")==0)) pstmt.setfloat(z,rset.getfloat(z)); if ((type2.compareto("oid")==0)/* (type2.compareto("unknown")*/) pgsqlconn.setautocommit(false); pstmt.setblob(z,rset.getblob(z)); if (type2.compareto("double")==0) pstmt.setdouble(z,rset.getdouble(z)); pstmt.setblob(z,rset.getblob(z)); //Fin del for pstmt.execute(); pstmt.clearparameters(); pgsqlconn.commit() ; //Fin del try catch (SQLException sqle) System.out.println("Could not connect to the database(4) : " + sqle.getmessage()); try String entra; BufferedReader input = new BufferedReader( new InputStreamReader(System.in)); entra = input.readline(); catch (IOException e) System.out.println("Could not read: " + e.getmessage()); //Fin del While

//fin del try catch (SQLException sqle) System.out.println("Could not connect to the database (5): " + sqle.getmessage()); try String entra; BufferedReader input = new BufferedReader( new InputStreamReader(System.in)); entra = input.readline(); catch (IOException e) System.out.println("Could not read: " + e.getmessage()); catch (Exception ex) System.out.println("Error: "+ ex.tostring()); try String entra; BufferedReader input = new BufferedReader( new InputStreamReader(System.in)); entra = input.readline(); catch (IOException e) System.out.println("Could not read: " + e.getmessage()); //fin de la clase guarda_col() public static void main(string args[]) new DBConnection().connection(); //class