< Mariadb

MariaDB haladó

Szerző: Sallai András

Copyright © 2020, Sallai András

Szerkesztve: 2020, 2023

Licenc: CC BY-SA 4.0

Web: https://szit.hu

Több SQL utasítás egyszerre

Statement stmt = c.createStatement(); String sql1 = "create database vmi1"; String sql2 = "create database vmi2"; String sql3 = "create database vmi3"; stmt.addBatch(sql1); stmt.addBatch(sql2); stmt.addBatch(sql3); stmt.executeBatch();

Meta adatok

if (conn != null) { DatabaseMetaData meta = conn.getMetaData(); System.out.println("Driver név: " + meta.getDriverName()); }

Használható metódusok:

getCatalogSeparator()

getCatalogTerm()

getDatabaseProductName()

getDatabaseProductVersion()

getDriverName()

getDriverVersion()

getExtraNameCharacters()

getIdentifierQuoteString()

getNumericFunctions()

getProcedureTerm()

getSQLKeywords()

getSchemaTerm()

getSearchStringEscape()

getStringFunctions()

getSystemFunctions()

getTimeDateFunctions()

getURL()

getUserName()

Beszúrt rekord kulcsa

String sql = "insert into tabla1 (name) values(?)"; PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); pstmt.setString(1, "János") pstmt.execute(); ResultSet rs = pstmt.getGeneratedKeys(); int genKey = 0; if (rs.next()) { genKey = rs.getInt(1); } System.out.println("az: " + genKey);

SQL problémák naplózása

import java.util.logging.Level; import java.util.logging.Logger; //... try { //... }catch(SQLException ex) { Logger.getLogger(Mariadb.class.getName()).log(Level.SEVERE, null, ex); }

A „Mariadb” az az osztály, amelyben a kapcsolatot létrehozzuk.

Driver jelenléte

A MariaDB driver ellenőrzése:

Class.forName("org.mariadb.jdbc.Driver");
import java.sql.SQLException; import java.sql.Statement; import java.sql.Connection; import java.sql.ResultSet; import java.sql.DriverManager; import java.util.ArrayList; class App { public static ArrayList<Employee> getEmployees() { ArrayList<Employee> employeeList = new ArrayList<>(); Connection conn = null; try { Class.forName("org.mariadb.jdbc.Driver"); String url = "jdbc:mariadb://localhost:3306/surubt"; conn = DriverManager.getConnection(url, "surubt", "titok"); String sql = "select * from employees"; Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); while(rs.next()) { Employee emp = new Employee( rs.getInt("id"), rs.getString("name"), rs.getString("city"), rs.getDouble("salary"), rs.getDate("birth").toLocalDate() ); employeeList.add(emp); } }catch(SQLException ex) { System.err.println("Hiba! Az SQL művelet sikertelen!"); System.err.println(ex.getMessage()); }catch(ClassNotFoundException ex) { System.err.println("Hiba! A MariaDB driver nem található!"); System.err.println(ex.getMessage()); } return employeeList; } public static void main(String[] args) { ArrayList<Employee> employeeList; employeeList = getEmployees(); employeeList.forEach(emp -> { System.out.println(emp.name); }); } }