Prof. Edwar Saliba Júnior



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

SQL and Java. Database Systems Lecture 19 Natasha Alechina

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

D06 PROGRAMMING with JAVA

Tutorial c-treeace Web Service Using Java

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

CS 111 Classes I 1. Software Organization View to this point:

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

Comparing the Effectiveness of Penetration Testing and Static Code Analysis

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

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

Database Access from a Programming Language:

D06 PROGRAMMING with JAVA

public void setusername(string username) { this.username = username; } public void setname(string name) { this.name = name; }

Java Server Pages and Java Beans

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

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

Using JML to protect Java code against SQL injection. Johan Janssen June 26, 2007

Lecture J - Exceptions

Brazil + JDBC Juin 2001, douin@cnam.fr

Continuous Integration Part 2

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

Using NetBeans IDE to Build Quick UI s Ray Hylock, GISo Tutorial 3/8/2011

LSINF1124 Projet de programmation

CS506 Web Design and Development Solved Online Quiz No. 01

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

TECH TUTORIAL: EMBEDDING ANALYTICS INTO A DATABASE USING SOURCEPRO AND JMSL

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

SQL. Short introduction

public static void main(string[] args) { System.out.println("hello, world"); } }

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

JAVA Program For Processing SMS Messages

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

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Zebra and MapReduce. Table of contents. 1 Overview Hadoop MapReduce APIs Zebra MapReduce APIs Zebra MapReduce Examples...

Output: struct treenode{ int data; struct treenode *left, *right; } struct treenode *tree_ptr;

Creating a Simple, Multithreaded Chat System with Java

Course Objectives. Database Applications. External applications. Course Objectives Interfacing. Mixing two worlds. Two approaches

Website as Tool for Compare Credit Card Offers

About the Tutorial. Audience. Prerequisites. Disclaimer & Copyright. Apache Hive

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

2. Installieren des MySQL Workbench (Version ) 3. Unter Database > Manage Connection folgende Werte eintragen

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

CHAPTER 5 INTELLIGENT TECHNIQUES TO PREVENT SQL INJECTION ATTACKS

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

Software Construction

bbc Developing Service Providers Adobe Flash Media Rights Management Server November 2008 Version 1.5

The JAVA Way: JDBC and SQLJ

File I/O - Chapter 10. Many Stream Classes. Text Files vs Binary Files

Abstract. Introduction. Web Technology and Thin Clients. What s New in Java Version 1.1

Laboratory Module 8 Mining Frequent Itemsets Apriori Algorithm

Input / Output Framework java.io Framework

CS346: Database Programming.

Scala Programming Language

TP N 10 : Gestion des fichiers Langage JAVA

Mail User Agent Project

CS/CE 2336 Computer Science II

Reading Input From A File

Hadoop Integration Guide

Chapter 2 Introduction to Java programming

Extracting META information from Interbase/Firebird SQL (INFORMATION_SCHEMA)

Package sjdbc. R topics documented: February 20, 2015

Sample CSE8A midterm Multiple Choice (circle one)

SQL and programming languages

Financial Data Access with SQL, Excel & VBA

1 SQL Data Types and Schemas

Course Intro Instructor Intro Java Intro, Continued

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

A Brief Introduction to MySQL

Files and input/output streams

Question R11.3. R11.3 How do you open a file whose name contains a backslash, like c:\temp\output.dat?

JAVA - EXCEPTIONS. An exception can occur for many different reasons, below given are some scenarios where exception occurs.

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

J a v a Quiz (Unit 3, Test 0 Practice)

Webair CDN Secure URLs

Tutorial for Spring DAO with JDBC

Adding HTML5 to your Android applications. Martin Gunnarsson & Pär Sikö

Hadoop Integration Guide

Example of a Java program

Programming Database lectures for mathema

Using Web Security Scanners to Detect Vulnerabilities in Web Services

Big Data and Analytics by Seema Acharya and Subhashini Chellappan Copyright 2015, WILEY INDIA PVT. LTD. Introduction to Pig

Database Applications Recitation 10. Project 3: CMUQFlix CMUQ s Movies Recommendation System

AP Computer Science Java Subset

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Conditionals (with solutions)

Database Query 1: SQL Basics

Transcription:

package Conexao; 2 3 /** 4 * 5 * @author Cynthia Lopes 6 * @author Edwar Saliba Júnior 7 */ 8 import java.io.filenotfoundexception; 9 import java.io.ioexception; 10 import java.sql.sqlexception; 11 import java.sql.statement; 12 import java.sql.connection; 13 import java.sql.drivermanager; 14 import java.sql.resultset; 15 import java.io.bufferedreader; 16 import java.io.filereader; 17 import java.util.arraylist; 18 import java.util.logging.level; 19 import java.util.logging.logger; 20 21 public final class Database { 22 23 24 25 26 27 28 29 30 31 32 private Access informationdb; private Connection connectiondb; private Statement querydb; private boolean enablemessages; private final String c_database_file = "AjaxEx08.txt"; public Database() throws FileNotFoundException, ClassNotFoundException { FileReader file = new FileReader(c_DATABASE_FILE); BufferedReader reader = new BufferedReader(file); String databasename; databasename = reader.readline(); String password = reader.readline(); String host = reader.readline(); reader.close(); file.close(); this.informationdb = new Access(dataBaseName, password, host); this.connectiontodb(); this.enablemessages = false; catch (IOException ex) { Logger.getLogger(Database.class.getName()).log(Level. (Database.class.getName()).log(Level.SEVERE, null, ex); public Database(String databasename, String password, String host) { this.informationdb = new Access(dataBaseName, password, host); this.connectiontodb(); this.enablemessages = false; catch (Exception ex) { Logger.getLogger(Database.class.getName()).log(Level. (Database.class.getName()).log(Level.SEVERE, null, ex); public Database(Access info) { this.informationdb = info; this.enablemessages = false; public void connectiontodb() throws ClassNotFoundException { this.startdriver(); connectiondb = DriverManager.getConnection( this.informationdb.geturl(), this.informationdb.getusuario(), this.informationdb.getsenha()); System.out.println("Connection.println("Connection with database '" + this.informationdb.getnomebd() + "' sucess completed."); 1.1 of 7 2013.05.24 14:18:52

this.querydb = this.connectiondb.createstatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); catch (SQLException e) { System.out.println(e.toString());.println(e.toString()); public void startdriver() throws ClassNotFoundException { Class.forName("org.postgresql.Driver"); public void insertvalues(string tablename, String fieldsnames[], String fieldsvalues[]) String query = "INSERT INTO \"" " + tablename + "\" ("; query += returnfieldsnames(fieldsnames) + ")"; query += " VALUES("; query += returnvalues(fieldsvalues, true) + ")"; this.querydb.execute(query); this.connectiondb.commit(); public void deletevalues(string tablename, String condition) String query = "DELETE FROM \"" " + tablename + "\""; this.querydb.execute(query); this.connectiondb.commit(); public void updatevalues(string tablename, String fields[], String values[], String condition) String query = "UPDATE \"" " + tablename + "\" SET "; query += this.returnsetvalues(fields, values); this.querydb.execute(query); this.connectiondb.commit(); public boolean existrow(string table, String condition) boolean foundrow; String query = "SELECT 1 "; query += " FROM \"" " + table + "\""; foundrow = resultset.first(); return (foundrow); 2.1 of 7 2013.05.24 14:18:52

public void printselection(string table, String fields[], String condition) query += " FROM \"" " + table + "\""; while (resultset.next()) { String print = ""; for (int i = 0; i < fields.length; i++) { print += " " + resultset.getstring(fields[i]) + " \t"; System.out.println(print);.println(print); public ArrayList selection(string table, boolean putquotationmarksonthefields, String fields[], String condition) { ArrayList resultslist = new ArrayList(); if (putquotationmarksonthefields) { else { query += returnvalues(fields, putquotationmarksonthefields); query += " FROM " + table; resultset.beforefirst(); while (resultset.next()) { String[] row = new String[resultSet.getMetaData().getColumnCount()]; for (int i = 0; i < resultset.getmetadata().getcolumncount(); i++) { row[i] = resultset.getstring(i + 1); resultslist.add(row); catch (SQLException ex) { System.out.println("Exceção.println("Exceção SQL: " + ex); return resultslist; public ResultSet selection(string table, String fields[], boolean putquotationmarksonthefields, String condition, boolean pointertofirstrecord) if (putquotationmarksonthefields) { else { query += returnvalues(fields, putquotationmarksonthefields); query += " FROM \"" " + table + "\""; 3.1 of 7 2013.05.24 14:18:52

if(pointertofirstrecord){ resultset.next(); return (resultset); public ResultSet selection(string query) resultset.next(); return (resultset); public void printjoinselection(string tables[], String fields[], String condition) query += " FROM " + returnfieldsnames(tables); for (int i = 0; i < fields.length; i++) { int dotposition = fields[i].indexof('.'); fields[i] = fields[i].substring(dotposition + 1, fields[i].length()); while (resultset.next()) { String print = ""; for (int i = 0; i < fields.length; i++) { print += " " + resultset.getstring(fields[i]) + " \t"; System.out.println(print);.println(print); public String returnvalues(string values[], boolean putquotationmarks) { String vals = ""; if (putquotationmarks) { vals += "\'" " + values[i] + "\', "; vals += "\'" " + values[values.length - 1] + "\'"; else { vals += values[i] + ", "; vals += values[values.length - 1]; return vals; public String returnfieldsnames(string values[]) { String vals = "\""; vals += values[i] + "\", \""; vals += values[values.length - 1] + "\""; return vals; 4.1 of 7 2013.05.24 14:18:52

public String returnsetvalues(string fields[], String values[]) { String vals = ""; vals += "\"" " + fields[i] + "\" = " + (values[i].equals("")? "\'\'" : "\'" " + values[i] + "\'") + ", "; vals += "\"" " + fields[fields.length - 1] + "\" = " + (values[values.length - 1].equals("")? "\'\'" : "\'" + values[values.length - 1] + "\'"); return vals; /** * Converte um vetor de inteiros para um formato aceitável por um campo do * tipo "array" do PostgreSQL. * * @param Vetor de Inteiros * @return "'{ val1, val2,... '" */ public String converttostringarray(int v[]) { String vetor = ""; vetor += "{"; for (int i = 0; i < v.length; i++) { if ((i < (v.length - 1)) && (!((i > 0) && (String.valueOf(v[i]).equals("0"))))) (v[i]).equals("0"))))) { vetor += String.valueOf(v[i]) + ","; else { vetor += String.valueOf(v[i]); break; vetor += ""; return (vetor); /** * Converte um campo do tipo "array" do PostgreSQL (String) num vetor de * inteiros. * * @param "String" - Ex.: {0,80,17,71,13,0 * @return "int []" - Ex.: [0,80,17,71,13,0] */ public int[] converttointarray(string v) { v = v.trim(); int vetor[] = new int[v.split(",", -1).length]; int j = 0; String n = ""; for (int i = 0; i < v.length(); i++) { if ((v.charat(i)!= '{') && (v.charat(i)!= '')) { if ((v.charat(i)!= ',') && (v.charat(i)!= ' ')) { n += v.substring(i, i + 1); else { vetor[j++] = Integer.parseInt(n); n = ""; return (vetor); public void closedbconnection() this.connectiondb.close(); public boolean isenablemessages() { return enablemessages; public void setenablemessages(boolean enablemessages) { 5.1 of 7 2013.05.24 14:18:52

this.enablemessages = enablemessages; @Override public void finalize() throws SQLException, Throwable { super.finalize(); closedbconnection(); private Object getfieldvalue(string tablename, String fieldname, String condition) Object value = null; String fields[] = {fieldname; ResultSet rs = selection(tablename, fields, true, condition, true); if (rs.first()) { value = rs.getobject(fieldname); public String getstringfieldvalue(string tables, String fields, String condition) String value = ""; value = val.tostring(); public int getintfieldvalue(string tables, String fields, String condition) int value = 0; value = Integer.valueOf(val.toString()); public float getfloatfieldvalue(string tables, String fields, String condition) float value = 0; value = Float.valueOf(val.toString()); public boolean getbooleanfieldvalue(string tables, String fields, String condition) boolean value = false; value = Boolean.valueOf(val.toString()); public int getnumberofrowsintable(string table, boolean putquotation) ResultSet rs; 6.1 of 7 2013.05.24 14:18:52

if (putquotation) { rs = selection("select count(*) " + " FROM \"" " + table + "\""); else { rs = selection("select count(*) " + " FROM " + table); int value = rs.getint(1); return value; 7.1 of 7 2013.05.24 14:18:52