\documentclass[10pt,a4paper]{article} % Packages \usepackage{fancyhdr} % For header and footer \usepackage{multicol} % Allows multicols in tables \usepackage{tabularx} % Intelligent column widths \usepackage{tabulary} % Used in header and footer \usepackage{hhline} % Border under tables \usepackage{graphicx} % For images \usepackage{xcolor} % For hex colours %\usepackage[utf8x]{inputenc} % For unicode character support \usepackage[T1]{fontenc} % Without this we get weird character replacements \usepackage{colortbl} % For coloured tables \usepackage{setspace} % For line height \usepackage{lastpage} % Needed for total page number \usepackage{seqsplit} % Splits long words. %\usepackage{opensans} % Can't make this work so far. Shame. Would be lovely. \usepackage[normalem]{ulem} % For underlining links % Most of the following are not required for the majority % of cheat sheets but are needed for some symbol support. \usepackage{amsmath} % Symbols \usepackage{MnSymbol} % Symbols \usepackage{wasysym} % Symbols %\usepackage[english,german,french,spanish,italian]{babel} % Languages % Document Info \author{victorjfg} \pdfinfo{ /Title (acceso-a-bases-de-datos-relacionales-en-java.pdf) /Creator (Cheatography) /Author (victorjfg) /Subject (Acceso a bases de datos relacionales en Java. Cheat Sheet) } % Lengths and widths \addtolength{\textwidth}{6cm} \addtolength{\textheight}{-1cm} \addtolength{\hoffset}{-3cm} \addtolength{\voffset}{-2cm} \setlength{\tabcolsep}{0.2cm} % Space between columns \setlength{\headsep}{-12pt} % Reduce space between header and content \setlength{\headheight}{85pt} % If less, LaTeX automatically increases it \renewcommand{\footrulewidth}{0pt} % Remove footer line \renewcommand{\headrulewidth}{0pt} % Remove header line \renewcommand{\seqinsert}{\ifmmode\allowbreak\else\-\fi} % Hyphens in seqsplit % This two commands together give roughly % the right line height in the tables \renewcommand{\arraystretch}{1.3} \onehalfspacing % Commands \newcommand{\SetRowColor}[1]{\noalign{\gdef\RowColorName{#1}}\rowcolor{\RowColorName}} % Shortcut for row colour \newcommand{\mymulticolumn}[3]{\multicolumn{#1}{>{\columncolor{\RowColorName}}#2}{#3}} % For coloured multi-cols \newcolumntype{x}[1]{>{\raggedright}p{#1}} % New column types for ragged-right paragraph columns \newcommand{\tn}{\tabularnewline} % Required as custom column type in use % Font and Colours \definecolor{HeadBackground}{HTML}{333333} \definecolor{FootBackground}{HTML}{666666} \definecolor{TextColor}{HTML}{333333} \definecolor{DarkBackground}{HTML}{9AA360} \definecolor{LightBackground}{HTML}{F8F9F5} \renewcommand{\familydefault}{\sfdefault} \color{TextColor} % Header and Footer \pagestyle{fancy} \fancyhead{} % Set header to blank \fancyfoot{} % Set footer to blank \fancyhead[L]{ \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{C} \SetRowColor{DarkBackground} \vspace{-7pt} {\parbox{\dimexpr\textwidth-2\fboxsep\relax}{\noindent \hspace*{-6pt}\includegraphics[width=5.8cm]{/web/www.cheatography.com/public/images/cheatography_logo.pdf}} } \end{tabulary} \columnbreak \begin{tabulary}{11cm}{L} \vspace{-2pt}\large{\bf{\textcolor{DarkBackground}{\textrm{Acceso a bases de datos relacionales en Java. Cheat Sheet}}}} \\ \normalsize{by \textcolor{DarkBackground}{victorjfg} via \textcolor{DarkBackground}{\uline{cheatography.com/35914/cs/11962/}}} \end{tabulary} \end{multicols}} \fancyfoot[L]{ \footnotesize \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{LL} \SetRowColor{FootBackground} \mymulticolumn{2}{p{5.377cm}}{\bf\textcolor{white}{Cheatographer}} \\ \vspace{-2pt}victorjfg \\ \uline{cheatography.com/victorjfg} \\ \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Cheat Sheet}} \\ \vspace{-2pt}Published 5th June, 2017.\\ Updated 8th June, 2017.\\ Page {\thepage} of \pageref{LastPage}. \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Sponsor}} \\ \SetRowColor{white} \vspace{-5pt} %\includegraphics[width=48px,height=48px]{dave.jpeg} Measure your website readability!\\ www.readability-score.com \end{tabulary} \end{multicols}} \begin{document} \raggedright \raggedcolumns % Set font size to small. Switch to any value % from this page to resize cheat sheet text: % www.emerson.emory.edu/services/latex/latex_169.html \footnotesize % Small font. \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Drivers}} \tn \SetRowColor{white} \mymulticolumn{1}{x{17.67cm}}{En estos ejemplos se utiliza el SGBD {\bf{h2 database engine}}, aunque se puede utilizar el mismo mecanismo para cualquier otro sgbd, siempre que se disponga del driver.% Row Count 4 (+ 4) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{\seqsplit{http://www.h2database.com}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{x{7.5988 cm} x{9.6712 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{17.67cm}}{\bf\textcolor{white}{Interfaces y clases}} \tn % Row 0 \SetRowColor{LightBackground} {\emph{Connection}} (Interface) & Representa a una conexión desde la app hasta una base de datos. La conexión se obtiene solicitándola a la clase DriverManager \tn % Row Count 6 (+ 6) % Row 1 \SetRowColor{white} {\emph{PreparedStatement}} (Interface) & Un objeto que acepta una sentencia SQL escrita en una cadena y la precompila para ser ejecutada de manera eficiente múltiples veces, cambiando sus parámetros. Permite tener {\emph{placeholders}} (con la marca {\bf{?}}) para parametrizar la ejecución de la sentencia. También es muy útil para librarse de la mayor parte de intentos de ataque por inyección de código SQL. Se obtiene solicitándolo a una conexión. \tn % Row Count 25 (+ 19) % Row 2 \SetRowColor{LightBackground} \textasciitilde{}\textasciitilde{}{\emph{Statement}}\textasciitilde{}\textasciitilde{} (Interface) & {\bf{No recomendado por ser más susceptible a inyección de código que {\emph{PreparedStatement}}}}. Es un objeto que permite la ejecución de una sentencia SQL. \tn % Row Count 32 (+ 7) \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{x{7.5988 cm} x{9.6712 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{17.67cm}}{\bf\textcolor{white}{Interfaces y clases (cont)}} \tn % Row 3 \SetRowColor{LightBackground} {\emph{ResultSet}} & Un objeto que representa a los datos devueltos por una sentencia SELECT o similar. En realidad, es un cursor a los resultados. Sólo puede haber un ResultSet activo por cada Statement. \tn % Row Count 9 (+ 9) % Row 4 \SetRowColor{white} DriverManager & Gestiona los drivers jdbc cargados en la app. Permite obtener conexiones a una BD. \tn % Row Count 13 (+ 4) % Row 5 \SetRowColor{LightBackground} SQLException & Las excepciones lanzadas por los métodos de los objetos de jdbc. \tn % Row Count 16 (+ 3) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{17.67cm}}{Todas las interfaces y clases mencionadas están en el paquete java.sql.*} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{x{8.635 cm} x{8.635 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{17.67cm}}{\bf\textcolor{white}{Cadenas de conexión en h2}} \tn % Row 0 \SetRowColor{LightBackground} jdbc:h2:tcp://nombre\_maquina-o-ip/\textasciitilde{}/nombre\_bd & Conexión en modo servidor a una bd en la carpeta del usuario \tn % Row Count 4 (+ 4) % Row 1 \SetRowColor{white} \seqsplit{jdbc:h2:tcp://nombre\_maquina-o-ip/}./nombre\_bd & Conexión en modo servidor a una bd en la carpeta del servidor \tn % Row Count 8 (+ 4) % Row 2 \SetRowColor{LightBackground} jdbc:h2:tcp://nombre\_maquina-o-ip/d:\textbackslash{}programacion\textbackslash{}nombre\_bd & Conexión en modo servidor a una bd en una ruta absoluta en la máquina del servidor \tn % Row Count 13 (+ 5) % Row 3 \SetRowColor{white} jdbc:h2:/\textasciitilde{}/nombre\_bd & Conexión en modo embebido a una bd en la carpeta del usuario \tn % Row Count 17 (+ 4) % Row 4 \SetRowColor{LightBackground} \seqsplit{jdbc:h2:/./nombre\_bd} & Conexión en modo embebido a una bd en la carpeta del proyecto \tn % Row Count 21 (+ 4) % Row 5 \SetRowColor{white} jdbc:h2:d:\textbackslash{}programacion\textbackslash{}nombre\_bd & Conexión en modo embebido a una bd en una ruta absoluta \tn % Row Count 24 (+ 3) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{17.67cm}}{Cada SGBD tiene sus drivers. La sintaxis de las cadenas de conexión es dependiente del driver. Es decir, las cadenas de conexión a una BD en Oracle no tienen la misma estructura que en h2} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Secuencia simple para enviar una select}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{/{\emph{ EJEMPLO de conexión y envío de una sentencia SELECT}}/ \newline \newline // Paso 0: Cargar el driver. Sólo hay que hacerlo una vez \newline // Ojo: puede lanzar ClassNotFoundException \newline \seqsplit{Class.forName("org.h2.Driver");} \newline \newline // Declaramos referencias a las interfaces que usaremos. \newline Connection conn = null; // Representa a la conexión \newline PreparedStatement stmt = null; // Representa a la sentencia \newline ResultSet rs = null; // Solo para Select \newline try \{ \newline // PASO 1: Obtener conexion \newline conn = \seqsplit{DriverManager.getConnection(} \newline "jdbc:h2:tcp://localhost/\textasciitilde{}/test", // Cadena de conexión \newline "sa", "" // Usuario y contraseña \newline ); \newline \newline // Paso 2: Preparamos la sentencia. Podemos poner placeholders \newline // para ejecutar la sentencia parametrizada. \newline // Supongamos que queremos que la ciudad contenga una determinada \newline // cadena y la nota sea superior a un cierto número \newline \newline String buscaCiudad = "la"; // Ej: Que la ciudad contenga 'la' \newline double notaMinima = 6.0; // y la nota sea mayor o igual a 6 \newline \newline String sql = "SELECT nombre, apellido, nota" \newline + " from alumno where ciudad like ? and nota \textgreater{}= ?"; \newline stmt = \seqsplit{conn.prepareStatement(sql);} \newline \newline // Paso 2a: Sustituir los placeholders por valores \newline stmt.setString(1, "\%" + buscaCiudad + "\%"); \newline stmt.setDouble(2, notaMinima); \newline \newline // Paso 3: Ejecución de la query y obtención de los datos \newline rs = stmt.executeQuery(); \newline \newline // Paso 4 (Solo para select). Recorrer Los datos obtenidos. \newline while (rs.next()) \{ \newline String nombre = rs.getString("nombre"); // Se puede obtener el dato de \newline String ape = \seqsplit{rs.getString("apellido");} // una fila por nombre de columna \newline Double nota = rs.getDouble(3); // o por posición \newline \seqsplit{System.out.format(Locale.ROOT}, "\%-15s \%-15s \%.2f", \newline nombre, ape, nota); \newline \} \newline \} catch (SQLException ex) \{ \newline // Tomar las acciones necesarias para que el caso de uso continúe \newline ex.printStackTrace(); \newline \} finally \{ \newline try \{rs.close();\} catch (Exception ex) \{\}; \newline try \{stmt.close();\} catch (Exception ex) \{\}; \newline try \{conn.close();\} catch (Exception ex) \{\}; \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Otro ejemplo: Un insert}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{/{\emph{ EJEMPLO de conexión y envío de una sentencia INSERT }}/ \newline \newline // Paso 0: Cargar el driver. Sólo hay que hacerlo una vez \newline // Ojo: puede lanzar ClassNotFoundException \newline \seqsplit{Class.forName("org.h2.Driver");} \newline \newline \newline \newline // Declaramos referencias a las interfaces que usaremos. \newline Connection conn = null; // Representa a la conexión \newline PreparedStatement stmt = null; // Representa a la sentencia \newline try \{ \newline // PASO 1: Obtener conexion \newline conn = \seqsplit{DriverManager.getConnection(} \newline "jdbc:h2:tcp://localhost/\textasciitilde{}/test", // Cadena de conexión \newline "sa", "" // Usuario y contraseña \newline ); \newline \newline // Paso 2: Preparamos la sentencia. Ponemos placeholders para \newline // los valores. \newline \newline \newline String nombre = "Pepe"; \newline String apellido = "Pérez"; \newline double nota = 8.0; \newline \newline String sql = "INSERT INTO alumno(nombre, apellido, nota)" \newline + " VALUES(?, ?, ?)"; \newline stmt = \seqsplit{conn.prepareStatement(sql);} \newline \newline // Paso 2a: Sustituir los placeholders por valores \newline stmt.setString(1, nombre); \newline stmt.setString(2, apellido); \newline stmt.setDouble(3, nota); \newline \newline // Paso 3: Ejecución de la sentencia. \newline int filas = stmt.executeUpdate(); \newline // devuelve el numero de filas afectadas \newline \newline \} catch (SQLException ex) \{ \newline // Tomar las acciones necesarias para que el caso de uso continúe \newline ex.printStackTrace(); \newline \} finally \{ \newline try \{stmt.close();\} catch (Exception ex) \{\}; \newline try \{conn.close();\} catch (Exception ex) \{\}; \newline \} \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Consideraciones}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{La conexión puede dejarse abierta y lanzar varias sentencias en la misma conexión.} \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} \mymulticolumn{1}{x{17.67cm}}{La sentencia preparada puede reutilizarse, cambiando el valor de los placeholders con los setters y reejecutándola.} \tn % Row Count 5 (+ 3) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{Una sentencia sólo puede tener un resultset abierto. Es decir, si una sentencia se reejecuta, cualquier resultset previamente abierto y asociado a ella queda en un estado no definido.} \tn % Row Count 9 (+ 4) % Row 3 \SetRowColor{white} \mymulticolumn{1}{x{17.67cm}}{Al cerrar una sentencia se cierran los resultsets asociados, pero se recomienda cerrar los resultsets explícitamente con close() siempre que se pueda para liberar los recursos de la manera lo más eficiente posible.} \tn % Row Count 14 (+ 5) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{Igualmente, al cerrar una conexión se cierran las sentencias asociadas, pero se recomienda cerrarlas explícitamente.} \tn % Row Count 17 (+ 3) % Row 5 \SetRowColor{white} \mymulticolumn{1}{x{17.67cm}}{La apertura y cierre de la conexión suele ser una operación costosa. En algunos contextos no se recomienda abrir y cerrar las conexiones en cada operación.} \tn % Row Count 21 (+ 4) % Row 6 \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{Para optimizar el uso de conexiones permanentemente abiertas, por ejemplo en el contexto de las aplicaciones web, se suelen utilizar \{\{link="https://es.wikipedia.org/wiki/Connection\_pool"\}\}pools de conexiones\{\{/link\}\}} \tn % Row Count 26 (+ 5) \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{x{2.1931 cm} x{7.4228 cm} x{7.2541 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{17.67cm}}{\bf\textcolor{white}{SGBD-R}} \tn % Row 0 \SetRowColor{LightBackground} h2 & Un sgbd pequeño, ligero y muy fiable y portable completamente construido en Java. & \seqsplit{http://www.h2database.com} \tn % Row Count 5 (+ 5) % Row 1 \SetRowColor{white} \seqsplit{Apache} Derby & Otro sgbd-r de la fundación apache. Escrito en Java. & \seqsplit{https://db.apache.org/derby/} \tn % Row Count 9 (+ 4) % Row 2 \SetRowColor{LightBackground} \seqsplit{Oracle} & Grande entre los grandes & \seqsplit{https://www.oracle.com/database/index.html} \tn % Row Count 12 (+ 3) % Row 3 \SetRowColor{white} MySQL & Popular durante mucho tiempo por ser bastante eficiente y económica. Muy utilizada en la web. Hoy es un producto de Oracle. Va cayendo en decadencia en favor de MariaDB & \seqsplit{https://www.mysql.com/} \tn % Row Count 22 (+ 10) % Row 4 \SetRowColor{LightBackground} \seqsplit{MariaBD} & SGBD de funcionamiento similar a MySQL & \seqsplit{https://mariadb.org/} \tn % Row Count 25 (+ 3) % Row 5 \SetRowColor{white} SQL \seqsplit{Server} & De Microsoft. Otro grande entre los grandes. Se integra facilmente con los productos de desarrollo de Microsoft (Visual Studio IDE, C\#, Visual Basic.NET, etc) & \seqsplit{https://www.microsoft.com/es-es/sql-server/} \tn % Row Count 35 (+ 10) \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{x{2.1931 cm} x{7.4228 cm} x{7.2541 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{17.67cm}}{\bf\textcolor{white}{SGBD-R (cont)}} \tn % Row 6 \SetRowColor{LightBackground} \seqsplit{Access} & De Microsoft. Prácticamente el único SGBD orientado a la ofimática con éxito comercial. & \seqsplit{https://products.office.com/es-es/access} \tn % Row Count 6 (+ 6) % Row 7 \SetRowColor{white} IBM DB2 & La solución SGBD-R de IBM & \seqsplit{https://www.ibm.com/analytics/us/en/technology/db2/} \tn % Row Count 9 (+ 3) % Row 8 \SetRowColor{LightBackground} \seqsplit{PostgreSQL} & Solución de código abierto. Muy popular en la web. Tiene fama de avanzado y fiable. & \seqsplit{https://www.postgresql.org/} \tn % Row Count 14 (+ 5) % Row 9 \SetRowColor{white} \seqsplit{SQLite} & El más popular de los peques. Pensado para ser embebido. Está escrito en C, por lo que va compilado a código nativo. & \seqsplit{https://www.postgresql.org/} \tn % Row Count 21 (+ 7) \hhline{>{\arrayrulecolor{DarkBackground}}---} \end{tabularx} \par\addvspace{1.3em} \end{document}