java - danciu gabrieldanciugabriel.ro/assets/files/cursul2_clase.pdf · configurari pentru mssql 1...
TRANSCRIPT
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: exempluclass 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);
System.out.println(" ee = " + Integer.toBinaryString(ee));
}
}
Rezultat:
b = -15
c = -1
d = -1
e = 15
f = 11110001
cc = 111100
dd = 111100
ee = 1111
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 claselorclass 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 %
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);
}
}
Exemplu:
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 DBConnection
conn=DriverManager.getConnection(“jdbc:mysql://localhost/MyDB”,
“user”, “password”);
• Inchide conexiunea catre DBif(conn!=null)
conn.close();
Configurari pentru MSSQL1 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: 300006 On the IP Addresses tab, make the following selections.■ Active: Yes ■ TCP Dynamic Ports: 07 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 SQLEXPRESSpublic 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;UserID=gaby;Password=Parola12;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
• jdbc:sqlserver://danciugabyserver.database.windows.net:1433;database=DBFiles;user=gaby@danciugabyserver;password=Parola12;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.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ă.