Uso dei parametri SQL
Quando si crea un'istruzione SQL, è possibile creare parametri SQL per riutilizzare l'istruzione con valori diversi. Questa pratica può fornire dei vantaggi in termini di prestazioni. È possibile preparare istruzioni generiche per l'utilizzo di variabili denominate ed eseguire le istruzioni quando necessario, iterando i valori delle variabili e associando i valori alle variabili denominate in ogni iterazione.
Quando si utilizzano i metodi executeInsert o executeUpdate, l'utente associa i parametri nel metodo con il parametro bindParams. bindParams è costituito da un array di oggetti, che può corrispondere a una qualsiasi combinazione di Null, Integer, Long, Boolean, Float, Double, String o ByteBuffers. Di seguito, viene riportato un esempio:
Statement st = d.createStatement("UPDATE Account set Balance = ? WHERE AcctNo > ?");
try
{
st.prepare();
Object[] bindParams = {new Integer (2000), new Integer (100)};
st.executeUpdate(bindParams);
}
finally
{
st.close();
}
Quando si utilizza il metodo getCursor o execute, è possibile utilizzare il metodo Statement.bind per fornire i nomi per i parametri SQL. Il metodo bind() acquisisce il numero del parametro e il valore da assegnargli. Se si utilizza un numero esterno all'intervallo consentito, viene generata un'eccezione DatabaseException. Tutte le associazioni possono essere reimpostate tramite Statement.reset.
È possibile scegliere uno dei seguenti metodi per numerare i parametri:
-
Un punto interrogativo (?) nell'istruzione consente di numerare ogni parametro in modo sequenziale, iniziando da 1.
- Un punto interrogativo seguito da un numero intero (?NNN) nell'istruzione assegna a ogni parametro il numero NNN.
Di seguito, viene riportato un esempio di istruzione che utilizza parametri per creare un limite superiore e un limite inferiore, da poter definire ad ogni esecuzione dell'istruzione. In questo esempio, i parametri sono numerati in modo sequenziale.
Statement s = Database.createStatement("SELECT * FROM T WHERE a < ? AND a > ?");
s.prepare();
s.bind(1, upperBound);
s.bind(2, lowerBound);
Cursor c = s.getCursor();
Di seguito, viene riportata la stessa istruzione, eccetto i numeri espliciti specificati per i parametri:
Statement s = Database.createStatement("SELECT * FROM T WHERE a < ?5 AND a > ?12");
s.prepare();
s.bind(5, upperBound);
s.bind(12, lowerBound);
Cursor c = s.getCursor();
Il metodo Statement.getFormalName converte un indice del parametro in un nome di parametro SQL. Se si desidera che getFormalName restituisca il nome del parametro, è necessario fornire un nome nella query. Ad esempio, quando si richiama getFormalName(1), l'istruzione "SELECT * FROM T WHERE a = :a" restituisce :a. Se si utilizzano i parametri, quali il punto interrogativo (?), come segnaposto, getFormalName() non è in grado di restituire il nome del parametro. Ad esempio, getFormalName(1) non restituirà il nome del parametro in questa istruzione: "SELECT * FROM T WHERE a = ?"
Esempio di codice: creazione di un aggiornamento con parametri
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.database.*;
import net.rim.device.api.io.*;
import java.util.*;
public class ParameterizedUpdate extends UiApplication
{
public static void main(String[] args)
{
ParameterizedUpdate theApp = new ParameterizedUpdate();
theApp.enterEventDispatcher();
}
public ParameterizedUpdate()
{
pushScreen(new ParameterizedUpdateScreen());
}
}
class ParameterizedUpdateScreen extends MainScreen
{
Database d;
public ParameterizedUpdateScreen()
{
LabelField title = new LabelField("SQLite Parameterized Update Sample",
LabelField.ELLIPSIS |
LabelField.USE_ALL_WIDTH);
setTitle(title);
add(new RichTextField("Attempting to update data in " +
"MyTestDatabase.db on the SDCard."));
try
{
URI myURI = URI.create("file:///SDCard/Databases/SQLite_Guide/" +
"MyTestDatabase.db");
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement(
"UPDATE People SET Age=? WHERE Name=?");
st.prepare();
Hashtable ht = new Hashtable(2);
ht.put("Sophie", new Integer(10));
ht.put("Karen", new Integer(7));
Enumeration names = ht.keys();
Enumeration ages = ht.elements();
while (names.hasMoreElements())
{
Integer iAge = (Integer)ages.nextElement();
String strName = (String)names.nextElement();
st.bind(1,iAge.intValue());
st.bind(2,strName);
st.execute();
st.reset();
}
st.close();
d.close();
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
e.printStackTrace();
}
}
}
Esempio di codice: creazione di un inserimento con parametri
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.database.*;
import net.rim.device.api.io.*;
import java.util.*;
public class ParameterizedInsert extends UiApplication
{
public static void main(String[] args)
{
ParameterizedInsert theApp = new ParameterizedInsert();
theApp.enterEventDispatcher();
}
public ParameterizedInsert()
{
pushScreen(new ParameterizedInsertScreen());
}
}
class ParameterizedInsertScreen extends MainScreen
{
Database d;
public ParameterizedInsertScreen()
{
LabelField title = new LabelField("SQLite Insert Data " +
"Schema Sample",
LabelField.ELLIPSIS |
LabelField.USE_ALL_WIDTH);
setTitle(title);
add(new RichTextField("Attempting to insert data into " +
"MyTestDatabase.db on the SDCard."));
try
{
URI myURI = URI.create("file:///SDCard/Databases/SQLite_Guide/" +
"MyTestDatabase.db");
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement("INSERT INTO People(Name,Age) " +
"VALUES (?,?)");
st.prepare();
Hashtable ht = new Hashtable(4);
ht.put("Sophie", new Integer(6));
ht.put("Karen", new Integer(3));
ht.put("Kevin", new Integer(82));
ht.put("Cindy", new Integer(12));
Enumeration names = ht.keys();
Enumeration ages = ht.elements();
while (names.hasMoreElements())
{
String strName = (String)names.nextElement();
Integer iAge = (Integer)ages.nextElement();
st.bind(1,strName);
st.bind(2,iAge.intValue());
st.execute();
st.reset();
}
st.close();
d.close();
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
e.printStackTrace();
}
}
}
Le informazioni sono state utili? Inviateci i vostri commenti.