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ă.