My favorites | Sign in
Project Home Downloads Wiki Issues Source
Checkout   Browse   Changes    
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
package com.chuidiang.ejemplos.preparedstatement_mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
* Ejemplos con PreparedStatement
*
* @author Chuidiang
*
*/
public class EjemploPreparedStatement {

public static void main(String[] args) {
new EjemploPreparedStatement();
}

/** Conexion con la bd */
private Connection conexion = null;

/**
* PreparedStatement con el select por id, que se va a usar varias veces y
* por eso lo ponemos como atributo, para no crearlo localmente en el método
* cada vez que se llama al mismo
*/
private PreparedStatement psSelectConClave = null;

/**
* borra toda la tabla person e inserta mil registros con statement y con
* PreparedStatement, para comparar los tiempos.
*/
public EjemploPreparedStatement() {
estableceConexion();
insertaPreparedStatement();
int clave = insertaPreparedStatementGetClave();
selectPreparedStatement(clave);
updatePreparedStatement(clave);
}

/**
* Establece la conexión con la bd.
*/
private void estableceConexion() {
try {
Class.forName("com.mysql.jdbc.Driver");

// Es necesario useServerPrepStmts=true para que los
// PreparedStatement
// se hagan en el servidor de bd. Si no lo ponemos, funciona todo
// igual, pero los PreparedStatement se convertirán internamente a
// Statements.
conexion = DriverManager.getConnection(
"jdbc:mysql://localhost/hibernate?useServerPrepStmts=true",
"hibernate", "hibernate");
} catch (Exception e) {
e.printStackTrace();
}

}

/**
* Inserta un registro
*/
private void insertaPreparedStatement() {
try {
PreparedStatement ps = conexion
.prepareStatement("insert into person values (null,?,?,?)");
ps.setInt(1, 22);
ps.setString(2, "Juan");
ps.setString(3, "Perez");
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}

/**
* Inserta un registro y devuelve la clave que se genera para dicho
* registro.
*
* @return La clave generada
*/
private int insertaPreparedStatementGetClave() {
int claveGenerada = -1;
try {
PreparedStatement ps = conexion.prepareStatement(
"insert into person values (null,?,?,?)",
PreparedStatement.RETURN_GENERATED_KEYS);
ps.setInt(1, 22);
ps.setString(2, "Juan");
ps.setString(3, "Perez");
ps.executeUpdate();

// Se obtiene la clave generada
ResultSet rs = ps.getGeneratedKeys();
while (rs.next()) {
claveGenerada = rs.getInt(1);
System.out.println("Clave generada = " + claveGenerada);
}
} catch (SQLException e) {
e.printStackTrace();
}
return claveGenerada;
}

/**
* Crea si no lo esta ya un PreparedStatement con un select por clave y lo
* ejecuta.
*
* @param clave
* La clave del registro que se quiere consultar.
*/
private void selectPreparedStatement(int clave) {
try {
if (null == psSelectConClave) {
psSelectConClave = conexion
.prepareStatement("select * from person where person_id=?");
}
psSelectConClave.setInt(1, clave);
ResultSet rs = psSelectConClave.executeQuery();
while (rs.next()) {
System.out.println("Clave=" + rs.getInt(1) + " Edad="
+ rs.getInt(2) + " Nombre=" + rs.getString(3)
+ " Apellido=" + rs.getString(4));
}
} catch (SQLException e) {
e.printStackTrace();
}
}

/**
* Modifica el registro cuya clave se le pasa usando un PreparedStatement.
*
* @param clave
* Clave del registro que se quiere modificar
*/
private void updatePreparedStatement(int clave) {
try {
PreparedStatement ps = conexion
.prepareStatement("update person set firstname=? where person_id=?");
ps.setString(1, "nuevo nombre");
ps.setInt(2, clave);
ps.executeUpdate();
System.out.println("modificado");
selectPreparedStatement(clave);

} catch (SQLException e) {
e.printStackTrace();
}
}
}

Change log

r58 by chuidiang on Jul 26, 2009   Diff
Ejemplo prepared statement
Go to: 
Project members, sign in to write a code review

Older revisions

All revisions of this file

File info

Size: 4971 bytes, 154 lines
Powered by Google Project Hosting