Java. Curs 2. Danciu Gabriel Mihail. Septembrie 2018

Similar documents
Java Database Connectivity (JDBC) 25.1 What is JDBC?

C:/Users/zzaier/Documents/NetBeansProjects/WebApplication4/src/java/mainpackage/MainClass.java

Topic 12: Database Programming using JDBC. Database & DBMS SQL JDBC

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer

Preview from Notesale.co.uk Page 21 of 162

Module - 3 Classes, Inheritance, Exceptions, Packages and Interfaces. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Unit 3 - Java Data Base Connectivity

BoxDemo1.java jueves, 02 de diciembre de :31

Roll Number. Common to II Year B.E.CSE & EIE INTERNAL ASSESSMENT TEST - I. Credit 3 R-2017

CSCI/CMPE Object-Oriented Programming in Java JDBC. Dongchul Kim. Department of Computer Science University of Texas Rio Grande Valley

CSC System Development with Java. Database Connection. Department of Statistics and Computer Science. Budditha Hettige

SQream Connector JDBC SQream Technologies Version 2.9.3

Cập nhật ResultSet trong JDBC

This lecture. Databases - JDBC I. Application Programs. Database Access End Users

Java Database Connectivity

VanillaCore Walkthrough Part 1. Introduction to Database Systems DataLab CS, NTHU

ERwin and JDBC. Mar. 6, 2007 Myoung Ho Kim

Accessing databases in Java using JDBC

Enterprise Java Unit 1- Chapter 6 Prof. Sujata Rizal

COP4540 TUTORIAL PROFESSOR: DR SHU-CHING CHEN TA: H S IN-YU HA

Java Database Connectivity

Oracle Exam 1z0-809 Java SE 8 Programmer II Version: 6.0 [ Total Questions: 128 ]

Databases and JDBC. by Vlad Costel Ungureanu for Learn Stuff

CSC 1214: Object-Oriented Programming

CONFIGURAREA UNUI SERVER IRC IN LINUX. Bica Bogdan *

Curs practic de Java

JDBC, Transactions. Niklas Fors JDBC 1 / 38

Tiers (or layers) Separation of concerns

Servlet 5.1 JDBC 5.2 JDBC

Visit for more.

Database connectivity (II)

You write standard JDBC API application and plug in the appropriate JDBC driver for the database the you want to use. Java applet, app or servlets

Calling SQL from a host language (Java and Python) Kathleen Durant CS 3200

UNIT-3 Java Database Client/Server

MYcsvtu Notes. Java Programming Lab Manual

Web Applications and Database Connectivity using JDBC (Part II)

How to program applications. CS 2550 / Spring 2006 Principles of Database Systems. SQL is not enough. Roadmap

Laborator 8 Java Crearea claselor de obiecte. Variabilele (campurile) clasei de obiecte

e-pg Pathshala Subject: Computer Science Paper: Web Technology Module: JDBC INTRODUCTION Module No: CS/WT/26 Quadrant 2 e-text

MANTHLY TEST SEPTEMBER 2017 QUESTION BANK CLASS: XII SUBJECT: INFORMATICS PRACTICES (065)

Cyrus Shahabi Computer Science Department University of Southern California C. Shahabi

Application Programming for Relational Databases

SQL and Java. Database Systems Lecture 20 Natasha Alechina

JDBC Drivers Type. JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server.

Programming in Java

DATABASE DESIGN I - 1DL300

Databases 2012 Embedded SQL

B2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA

CSE 135. Three-Tier Architecture. Applications Utilizing Databases. Browser. App. Server. Database. Server

3) execute() Usage: when you cannot determine whether SQL is an update or query return true if row is returned, use getresultset() to get the

Inherit a class, you simply incorporate the definition of one class into another by using the extends keyword.

DataBase Lab JAVA-DATABASE CONNECTION. Eng. Haneen El-masry

General Overview - rel. model. Carnegie Mellon Univ. Dept. of Computer Science Database Applications. Reminder: our Mini-U db

BUSINESS INTELLIGENCE LABORATORY. Data Access: Relational Data Bases. Business Informatics Degree

Aplicatii JAVA. JAVA Lucrul cu baze de date în Java # 10. Adrian Runceanu

Three-Tier Architecture

Departamento de Lenguajes y Sistemas Informáticos

What is Transaction? Why Transaction Management Required? JDBC Transaction Management in Java with Example. JDBC Transaction Management Example

Chapter 10 Java and SQL. Wang Yang

Chapter 1 An introduction to relational databases and SQL

Database Programming Overview. COSC 304 Introduction to Database Systems. Database Programming. JDBC Interfaces. JDBC Overview

Introduction to SQL & Database Application Development Using Java

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Information Science and Engineering

Enterprise Systems. Lecture 02: JDBC. Behzad BORDBAR

JDBC Architecture. JDBC API: This provides the application-to- JDBC Manager connection.

Accessing a database from Java. Using JDBC

1. PhP Project. Create a new PhP Project as shown below and click next

IT Certification Exams Provider! Weofferfreeupdateserviceforoneyear! h ps://

Exam Questions 1Z0-809

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

Java Lecture Note. Prepared By:

SQL: Programming. Announcements (September 25) Motivation. CPS 116 Introduction to Database Systems. Pros and cons of SQL.

Third Year Diploma Courses in Computer Science & Engineering, Computer Engineering, Computer Technology & Information Technology Branch.

The Java programming environment. The Java programming environment. Java: A tiny intro. Java features

Introduction to Java Development with IDS

access to a JCA connection in WebSphere Application Server

SNS COLLEGE OF ENGINEERING, Coimbatore

1SFWJFX FYDMVTJWF FYDFSQUT GSPN CSBOE OFX BOE GPSUIDPNJOH 0SBDMF 1SFTT +BWB +%, CPPLT

Formatting Output & Enumerated Types & Wrapper Classes

Part I: Stored Procedures. Introduction to SQL Programming Techniques. CSC 375, Fall 2017

H212 Introduction to Software Systems Honors

Types of Databases. Types of Databases. Types of Databases. Databases and Web. Databases and Web. Relational databases may also have indexes

3. The pool should be added now. You can start Weblogic server and see if there s any error message.

UNIT III - JDBC Two Marks

1Z Java SE 8 Programmer II. Version: Demo

EMBEDDED SQL. SE 3DB3 Fall 2016 MICHAEL LIUT DEPARTMENT OF COMPUTING AND SOFTWARE MCMASTER UNIVERSITY

Crash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++

Chapter 16: Databases

Example packages from Java s standard class library:

S.E. Sem. III [CMPN] Object Oriented Programming Methodology

Fundamentals of Programming Data Types & Methods

Chapter 2: Basic Elements of Java

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA

Embedded SQL. csc343, Introduction to Databases Diane Horton with examples from Ullman and Widom Fall 2014

SQL-PL Interface. Murali Mani. Perl /CGI with Oracle/mySQL Install your own web server and use servlets with JDBC and Oracle/mySQL

JDeveloper. Read Lotus Notes Data via URL Part 2

Databases and SQL Lab EECS 448

SQL in a Server Environment

The Design of JDBC The Structured Query Language Basic JDBC Programming Concepts Query Execution Scrollable and Updatable Result Sets

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Transcription:

Java Curs 2 Danciu Gabriel Mihail Septembrie 2018

Cuprins Operatori Clase Pachete Prezentare java.lang Introducere în baze de date

Operatori aritmetici

Operatorii pe biţi

Operatori pe biţi: exemplu class ByteUShift { static public void main(string args[]) { byte b = (byte) 0xF1; System.out.println(" b = " + b); byte c = (byte) (b >> 4); System.out.println(" c = " + c); byte d = (byte) (b >>> 4); System.out.println(" d = " + d); byte e = (byte) ((b & 0xFF) >> 4); System.out.println(" e = " + e); short f = (short) 0xF1; System.out.println(" f = " + Integer.toBinaryString(f)); short cc = (short ) (f >> 2); System.out.println(" cc = " + Integer.toBinaryString(cc)); short dd = (short ) (f >>> 2); System.out.println(" dd = " + Integer.toBinaryString(dd)); short ee = (short) ((f & 0xFF) >> 4); Rezultat: b = -15 c = -1 d = -1 e = 15 f = 11110001 cc = 111100 dd = 111100 ee = 1111 System.out.println(" ee = " + Integer.toBinaryString(ee));

Operatori relaţionali

Operatori logici

Precendenţa operatorilor

Clase class ClassName { type instance-variable1; type instance-variable2; //... type instance-variablen; type methodname1(parameter-list) { // body of method type methodname2(parameter-list) { // body of method //... type methodnamen(parameter-list) { // body of method

Clase exemplu class Box { double width; double height; double depth; class Box { double width; double height; double depth; public double ComputeVolume() { return width*height*depth;

Utilizarea claselor class BoxDemo { public static void main(string args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // assign values to mybox1's instance variables mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; /* assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; // compute volume of first box vol = mybox1.width * mybox1.height * mybox1.depth; System.out.println("Volume is " + vol); // compute volume of second box System.out.println("Volume is " + mybox2.computevolume()); Rezultat Volume is 3000.0 Volume is 162.0

Pachete package MyPackage; package pkg1[.pkg2[.pkg3]]; == structura de directoare: pkg1/pkg2/pkg3 package java.awt.image; CLASSPATH C:> set CLASSPATH=classpath1;classpath2... Echo % CLASSPATH % Exemplu: package MyPack; class Balance { String name; double bal; Balance(String n, double b) { name = n; bal = b; void show() { if(bal<0) System.out.print("--> "); System.out.println(name + ": $" + bal);

Pachete - acces

Pachete -import import pkg1 [.pkg2].(classname *); import java.util.date; import java.io.*;

java.lang - introducere Clase: Interfete:

Wrapper Double double Referinta primitiv

Wrapers Byte, Short, Integer, and Long Number Double and Float Character Boolean

Clase din java.lang Process Runtime ProcessBuilder System Object Class ClassLoader Math Compiler Thread, ThreadGroup, and Runnable Package Throwable RuntimePermission SecurityManager StackTraceElement

Clasa System

System

System - exemplu class Elapsed { public static void main(string args[]) { long start, end; System.out.println("Timing a for loop from 0 to 100,000,000"); // time a for loop from 0 to 100,000,000 start = System.currentTimeMillis(); // get starting time for(long i=0; i < 100000000L; i++) ; end = System.currentTimeMillis(); // get ending time System.out.println("Elapsed time: " + (end-start));

Citire de la tastatura (Scanner) import java.util.*; class A { public static void main(string[] args) { System.out.println("Enter your username: "); Scanner scanner = new Scanner(System.in); String username = scanner.nextline(); System.out.println("Your username is " + username);

JDBC conectare la DB Import pachete: import java.sql.* Inregistrarea driver-ului JDBC: Class.forName("com.mysql.jdbc.Driver"); Deschide conexiunea catre DB Connection conn=drivermanager.getconnection( jdbc:mysql://localhost/mydb, user, password ); Inchide conexiunea catre DB if(conn!=null) conn.close();

Configurari pentru MSSQL 1 Select Start > All Programs > Microsoft SQL Server > Configuration Tool > SQL Server Configuration Manager. 2 Select SQL Server Network Configuration > Protocols for <Instance name>. 3 Enable TCP/IP. 4 Open TCP/IP Properties. 5 On the Protocol tab, make the following selections. Enabled: Yes Listen All: Yes Keep Alive: 30000 6 On the IP Addresses tab, make the following selections. Active: Yes TCP Dynamic Ports: 0 7 Restart the SQL Server service from SQL Server Configuration Manager > SQL Server Services. 8 Start the SQL Server Browser service from SQL Server Configuration Manager > SQL Server Services.

Exemplu //STEP 1. Import required packages import java.sql.*; public class JDBCExample { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.driver"; static final String DB_URL = "jdbc:mysql://localhost/students"; // Database credentials static final String USER = "username"; static final String PASS = "password"; public static void main(string[] args) { Connection conn = null; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected database successfully..."); catch(sqlexception se){ //Handle errors for JDBC se.printstacktrace(); catch(exception e){ //Handle errors for Class.forName e.printstacktrace(); finally{ //finally block used to close resources try{ if(conn!=null) conn.close(); catch(sqlexception se){ se.printstacktrace(); //end finally try //end try System.out.println("Goodbye!"); //end main //end JDBCExample

Exemplu conexiune SQLEXPRESS public class Jdbc { static final String DB_URL = "jdbc:sqlserver://localhost\\sqlexpress;databasename=myfriends;user=sa;password=parola;integratedsecurity=false;"; public static void main(string[] args) { Connection conn = null; try { System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(DB_URL); System.out.println("Connected database successfully..."); //TODO: add code that SELECTS INSERTS UPDATES and DELETES stuff in DB catch (SQLException se) { //Handle errors for JDBC se.printstacktrace(); catch (Exception e) { //Handle errors for Class.forName e.printstacktrace(); finally { //finally block used to close resources try { if (conn!= null) { conn.close(); catch (SQLException se) { se.printstacktrace(); //end finally try //end try System.out.println("Goodbye!");

Conexiuni la DBFiles Server=tcp:danciugabyserver.database.windows.net,1433;Initial Catalog=DBFiles;Persist Security Info=False;User ID=gaby;Password=Parola12;MultipleActiveResultSets=False;Encrypt= True;TrustServerCertificate=False;Connection Timeout=30; jdbc:sqlserver://danciugabyserver.database.windows.net:1433;datab ase=dbfiles;user=gaby@danciugabyserver;password=parola12;encry pt=true;trustservercertificate=false;hostnameincertificate=*.databas e.windows.net;logintimeout=30;

Select import the packages: Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice. Register the JDBC driver: Requires that you initialize a driver so you can open a communications channel with the database. Open a connection: Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server. Execute a query: Requires using an object of type Statement for building and submitting an SQL statement to select (i.e. fetch ) records from a table. Extract Data: Once SQL query is executed, you can fetch records from the table. Clean up the environment: Requires explicitly closing all database resources versus relying on the JVM's garbage collection.

SELECT (inlocuit //TODO) Statement stmt = null; System.out.println("Creating statement..."); stmt = conn.createstatement(); String sql = "SELECT [PersonId],[Name],[Address] FROM [myfriends].[dbo].[people]"; ResultSet rs = stmt.executequery(sql); //STEP 5: Extract data from result set Person[] persons = new Person[10]; int index = 0; while (rs.next()) { //Retrieve by column name Person p = new Person(); p.id = rs.getint("personid"); p.name = rs.getstring("name"); p.adress = rs.getstring("address"); persons[index++] = p; rs.close(); for(person person : persons) System.out.println(person);

Rezultat Connecting to a selected database... Connected database successfully... Creating statement... 1 John Smith Hollywood 2 Samuel Clemens Australia 3 Samuel Clemens USA 4 John Smith Hollywood 5 Samuel Clemens Australia 6 Samuel Clemens USA null null null null Goodbye!

Exerciții Folosind comenzile INSERT UPDATE si DELETE cu ajutorul: https://www.w3schools.com/sql/default.asp, scrieți câte o funcție pentru: inserarea unui obiect de tip Person in tabela din baza de date modificarea numelui acelei persoane ștergerea acelei persoane din tabelă Scrieți câte o funcție pentru: Afișarea tuturor persoanelor care încep cu o anumită literă. Litera se va citi de la tastatură înainte de SELECT Modificarea numelui persoanelor în tabelă: orice nume va începe cu literă mare Ștergerea tuturor persoanelor cu un ID mai mic decât un anumit număr. Numărul se va citi de la tastatură.