SQL-Befehle mit Java
Wie lautet der Code wenn man in Java auf SQL zugreifen will und XYZ machen will.
Wie lautet der Code wenn man in Java auf SQL zugreifen will und XYZ machen will.
-
- 1 / 31
-
Lernkarten
Datenbankverbindung erstellen:
- www.myurl.com auf port # 4000 books
- Kein localhost
- Auf Port 4000
- Aufgabe: 1-3 Linien Code schreiben um eine Verbindung mit dieser DB zu erstellen
Connection con = DriverManager.get Connection(www.myurl.com:4000/books”, “Username”, “Passwort”);
alternativ
String url “jdbc:mysql:// www.myurl.com:4000/books
What is Metadata?
- Metadata is data that describes other data.
- Metadata summarizes basic information about data, which can make finding and working with particular instances of data easier
SQL-Code um eine Datenbank "company" zu erstellen
CREATE DATABASE COMPANY
Tabelle "employee" erstellen mit Attributen
- Empno als Primärschlüssel
- Firstname
- Lastname
- Workdept
- Phone
- Hiredate
- Gender
- Birthdate
- Salary
CREATE TABLE employee (EMPNO int NOT NULL, FIRSTNAME varchar(20), LASTNAME varchar(20), Workdept int, PHONE varchar(10), HIREDATE date, GENDER char(1), BIRTHDATE date, SALARY double);
Insert a record into employee
- EMPNO = 2
- FIRSTNAME = Mary
- LASTNAME = Kain
- WORKDEPT = 100
- PHONE = 18901
- HIREDATE = 1984-08-22
- GENDER = W
- BIRTHDATE = 1968-11-12
- SALARY = 7195
INSERT INTO employee VALUES (2,'Mary','Kain',100,'18901','1984-08-22','w','1968-11-12',7195);
--> bei int-Werten ohne ' '
--> bei Char, VarChar und Date mit ' '
What do you need to access a Database through a Java Program?
A "Database" JDBC Driver and a JDBC API
Was ist ein JDBC API?
JDBC ist die Abkürzung für Java Database Connectivity. Die JDBC-API ermöglicht den Zugriff auf RDBMS (relationale Datenbankmanagementsysteme) mittels Java und SQL.
Die JDBC-API residiert in folgenden Packages:
- java.sql
- javax.sql (erweitert JDBC um Server-Side-Möglichkeiten)
The Java Database Connectivity (JDBC) API provides universal data access from the Java programming language. Using the JDBC API, you can access virtually any data source, from relational databases
Was ist ein JDBC Driver?
Um die Möglichkeit zu schaffen, dass man Datenbanksysteme mittels eines einheitlichen Interfaces, nämlich der JDBC-API, ansprechen kann, bedarf es noch mindestens einer Zwischenschicht.
Diese Zwischenschicht oder zumindest einen Teil davon stellen die JDBC-Datenbanktreiber dar. Man muss zuerst einen Treiber herunterladen, bevor man eine Verbindung zur DB macht.
Datenbankverbindung erstellen:
Verbindung mit der PostgreSQL-Datenbank testdb herstellen. Die Datenbank ist am lokalen Rechner (localhost) abgelegt und es wird der Standardport 5432 verwendet. Der Datenbankbenutzer soll "user" mit dem Passwort "password" sein.
try
{
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection("jdbc:postgresql:testdb", "user", "password");
conn.close();
}
catch(ClassNotFoundException e) {
}
catch(SQLException e) {
}
Die getConnection()-Methode der Klasse DriverManager gibt es mit verschiedenen Signaturen. Der erste Parameter ist immer erforderlich. Dabei handelt es sich um die sogenannte URL (Uniform Ressource Locator) der Datenbank. Diese URL beginnt immer mit jdbc:, dann folgt die Datenbankprotokoll-/Treiberidentifikation und abschließend noch die Angabe der Datenquelle.
Driver laden
String DRIVEr="com.mysql.jdbc.Driver";
Class.forName(Driver);
- Class.forName loads the driver
How is the structure of a DB connection code?
Making a connection to the DB server (assumption: driver is loaded):
- DB = mySQL
- on localhost
- Port 4000
- database name = company
structure:
- first always "jdbc"
- because we are connecting to a sql server second name is --> mysql
- location of the server: when it is on the local PC then --> localhost
- ODER: kann auch eine URL sein!!! -->
- port number to which mysql is listenting --> 3306
- can be different
- the database name i created --> company
Example: jdbc:mysql://localhost:4000/company
Create a connection for Database:
- mysql
- URL = www.myexample.com
- Port = 5000
- Database name = example
jdbc:mysql://www.myexample.com:5000/example
How is the Connection to the Database made?
by caeating a Connection object
Connection con = DriverManager.getConnection (database, "userid", "password");
- Database = name of the used Database
- userid = a valid username
- password = associated password
- if connection fails SQL error is thrown --> must be caught by a "try and catch"
For what are Statement objects used?
to execute Queries (zum Ausführen von Abfragen)
What is the code for a Statement?
Statement stmt = con.create Statement();
Load the Driver
String DRIVER=“com.mysql.jdbc.Driver“;
Class.forName (Driver);
Class.forName lädt den Treiber
Complete code to connect to a Database server
- localhost
- Port 5000
- Database company
- User = levin
- passwort = tiger
String Database=”jdbc:mysql://localhost:5000/company”
Con=DriverManager.getConnection(company, “levin”,”tiger”);
code to create a statement
statement stmt=con.createStatemen();
--> wird verwendet um ein Statement Object zu erstellen. Dieses benötigt man für SQL Abfragen.
code to execute the query string
string mySQL = "select * from employee";
ResultSet rs=stmt.executeQuery(mySQL);
Code to process the results of a Select query
while (rs.next ()) {
String name=rs.getString("Firstname")
System.out.prinln(name);
}
- while-Schleife damit Ergebnisse aberufen werden solange welche da sind
- String erstellen (hier "name") welcher den Firstname der Ergebnisse holt
- Ausgabe des Strings name
Find all databases on the server (SQL-Code)
show databases;
Use a database company in SQL
use company;
Create a database called company
CREATE DATABASE company;
Show which tables are available in a database in SQL
SHOW TABLES;
Create a table employee with firstname, lastname and birthdate in SQL
CREATE TABLE employee (firstname VARCHAR(20), lastname VARCHAR(20), birthdate DATE);
Delete a table in SQL
DROP TABLE tablename;
Insert one record into a table in SQL
INSERT INTO tablename VALUES ('Bob','Bentley','1984-02-02');
Getting records from a table
SELECT * FROM employee;
Find the structure of a table
DESCRIBE tablename;
Close a resultSet and a connection
rs.close();
con.close();
Load the driver, connect to a DB and create a statement
String DRIVER="com.mysql.jdbc.Driver";
class.forName (DRIVER);
String database="jdbc:mysql://localhost:4000/company";
Connection con = DriverManager.getConnection (database,"user","id");
statement stmt = con.createStatement();