Je n'arrive pas à trouver un exemple de code pour construire une base de données Berkeley en Java et y insérer des enregistrements. Des échantillons? Et je ne parle pas de Berkeley DB Java Edition non plus.Insertion d'enregistrements dans Berkeley DB avec Java
1
A
Répondre
3
Si vous téléchargez db-5.0.21.NC.zip vous verrez beaucoup d'échantillons. Voici un qui semble faire ce que vous voulez
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2004, 2010 Oracle and/or its affiliates. All rights reserved.
*
* $Id$
*/
// File: ExampleDatabaseLoad.java
package db.GettingStarted;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;
import com.sleepycat.bind.EntryBinding;
import com.sleepycat.bind.serial.SerialBinding;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.db.DatabaseEntry;
import com.sleepycat.db.DatabaseException;
public class ExampleDatabaseLoad {
private static String myDbsPath = "./";
private static File inventoryFile = new File("./inventory.txt");
private static File vendorsFile = new File("./vendors.txt");
// DatabaseEntries used for loading records
private static DatabaseEntry theKey = new DatabaseEntry();
private static DatabaseEntry theData = new DatabaseEntry();
// Encapsulates the databases.
private static MyDbs myDbs = new MyDbs();
private static void usage() {
System.out.println("ExampleDatabaseLoad [-h <database home>]");
System.out.println(" [-i <inventory file>] [-v <vendors file>]");
System.exit(-1);
}
public static void main(String args[]) {
ExampleDatabaseLoad edl = new ExampleDatabaseLoad();
try {
edl.run(args);
} catch (DatabaseException dbe) {
System.err.println("ExampleDatabaseLoad: " + dbe.toString());
dbe.printStackTrace();
} catch (Exception e) {
System.out.println("Exception: " + e.toString());
e.printStackTrace();
} finally {
myDbs.close();
}
System.out.println("All done.");
}
private void run(String args[])
throws DatabaseException {
// Parse the arguments list
parseArgs(args);
myDbs.setup(myDbsPath);
System.out.println("loading vendors db....");
loadVendorsDb();
System.out.println("loading inventory db....");
loadInventoryDb();
}
private void loadVendorsDb()
throws DatabaseException {
// loadFile opens a flat-text file that contains our data
// and loads it into a list for us to work with. The integer
// parameter represents the number of fields expected in the
// file.
List vendors = loadFile(vendorsFile, 8);
// Now load the data into the database. The vendor's name is the
// key, and the data is a Vendor class object.
// Need a serial binding for the data
EntryBinding dataBinding =
new SerialBinding(myDbs.getClassCatalog(), Vendor.class);
for (int i = 0; i < vendors.size(); i++) {
String[] sArray = (String[])vendors.get(i);
Vendor theVendor = new Vendor();
theVendor.setVendorName(sArray[0]);
theVendor.setAddress(sArray[1]);
theVendor.setCity(sArray[2]);
theVendor.setState(sArray[3]);
theVendor.setZipcode(sArray[4]);
theVendor.setBusinessPhoneNumber(sArray[5]);
theVendor.setRepName(sArray[6]);
theVendor.setRepPhoneNumber(sArray[7]);
// The key is the vendor's name.
// ASSUMES THE VENDOR'S NAME IS UNIQUE!
String vendorName = theVendor.getVendorName();
try {
theKey = new DatabaseEntry(vendorName.getBytes("UTF-8"));
} catch (IOException willNeverOccur) {}
// Convert the Vendor object to a DatabaseEntry object
// using our SerialBinding
dataBinding.objectToEntry(theVendor, theData);
// Put it in the database.
myDbs.getVendorDB().put(null, theKey, theData);
}
}
private void loadInventoryDb()
throws DatabaseException {
// loadFile opens a flat-text file that contains our data
// and loads it into a list for us to work with. The integer
// parameter represents the number of fields expected in the
// file.
List inventoryArray = loadFile(inventoryFile, 6);
// Now load the data into the database. The item's sku is the
// key, and the data is an Inventory class object.
// Need a tuple binding for the Inventory class.
TupleBinding inventoryBinding = new InventoryBinding();
for (int i = 0; i < inventoryArray.size(); i++) {
String[] sArray = (String[])inventoryArray.get(i);
String sku = sArray[1];
try {
theKey = new DatabaseEntry(sku.getBytes("UTF-8"));
} catch (IOException willNeverOccur) {}
Inventory theInventory = new Inventory();
theInventory.setItemName(sArray[0]);
theInventory.setSku(sArray[1]);
theInventory.setVendorPrice((new Float(sArray[2])).floatValue());
theInventory.setVendorInventory((new Integer(sArray[3])).intValue());
theInventory.setCategory(sArray[4]);
theInventory.setVendor(sArray[5]);
// Place the Vendor object on the DatabaseEntry object using our
// the tuple binding we implemented in InventoryBinding.java
inventoryBinding.objectToEntry(theInventory, theData);
// Put it in the database. Note that this causes our secondary database
// to be automatically updated for us.
myDbs.getInventoryDB().put(null, theKey, theData);
}
}
private static void parseArgs(String args[]) {
for(int i = 0; i < args.length; ++i) {
if (args[i].startsWith("-")) {
switch(args[i].charAt(1)) {
case 'h':
myDbsPath = new String(args[++i]);
break;
case 'i':
inventoryFile = new File(args[++i]);
break;
case 'v':
vendorsFile = new File(args[++i]);
break;
default:
usage();
}
}
}
}
private List loadFile(File theFile, int numFields) {
List records = new ArrayList();
try {
String theLine = null;
FileInputStream fis = new FileInputStream(theFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
while((theLine=br.readLine()) != null) {
String[] theLineArray = splitString(theLine, "#");
if (theLineArray.length != numFields) {
System.out.println("Malformed line found in " + theFile.getPath());
System.out.println("Line was: '" + theLine);
System.out.println("length found was: " + theLineArray.length);
System.exit(-1);
}
records.add(theLineArray);
}
fis.close();
} catch (FileNotFoundException e) {
System.err.println(theFile.getPath() + " does not exist.");
e.printStackTrace();
usage();
} catch (IOException e) {
System.err.println("IO Exception: " + e.toString());
e.printStackTrace();
System.exit(-1);
}
return records;
}
private static String[] splitString(String s, String delimiter) {
Vector resultVector = new Vector();
StringTokenizer tokenizer = new StringTokenizer(s, delimiter);
while (tokenizer.hasMoreTokens())
resultVector.add(tokenizer.nextToken());
String[] resultArray = new String[resultVector.size()];
resultVector.copyInto(resultArray);
return resultArray;
}
protected ExampleDatabaseLoad() {}
}
4
Il y a un certain nombre de bonnes guides de démarrage pour Oracle Berkeley DB Java Edition. Ils sont inclus dans l'ensemble de documentation. Vous trouverez un exemple de code dans la documentation. Si vous êtes nouveau dans Oracle Berkeley DB Java Edition, c'est le bon endroit pour commencer. Il y a d'autres exemples dans le package de téléchargement.
Je suis le chef de produit pour Oracle Berkeley DB, j'espère que cela répond à votre question. Si ce n'est pas le cas, faites-moi savoir comment je pourrais vous aider.
Questions connexes
- 1. problème berkeley compilation db java
- 2. Berkeley Java DB taille de cache
- 3. GUI pour Berkeley DB
- 4. Berkeley DB dans les applications multithread
- 5. Erreur de mutation dans Berkeley DB
- 6. puis-je utiliser bdb (berkeley db) fichier créé par l'implémentation c (python bsddb) par oracle berkeley db java édition?
- 7. Quelle est l'utilisation atomique de Berkeley DB?
- 8. Problème avec insertion en db avec ASP.NET
- 9. Berkeley DB: Récupérer uniquement les clés
- 10. Lecture en bloc avec Berkeley DB, interface STL C++
- 11. Berkeley Db migration de la plate-forme
- 12. Edition Berkeley DB Java, toutes les alternatives LGPL ou BSD en Java?
- 13. Partition Base de données API Berkeley DB SQL
- 14. Berkeley DB Java Edition - réglage pour une grande quantité de données
- 15. Berkeley DB: comment cela se compare-t-il à MongoDB?
- 16. Problème lors de l'ouverture de berkeley db en python
- 17. Est-ce que l'édition java de Berkeley DB supporte les vecteurs de sauvegarde
- 18. Est-ce que Berkeley DB (version Java) prend en charge le partitionnement de données?
- 19. berkeley db: comment puis-je supprimer plusieurs clés de données avec php 5?
- 20. insertion de chaîne de temps Date db
- 21. Problème avec Berkeley DB Base de données et bases de données secondaires JE Base API
- 22. Insertion d'une date dans un accès db en vb
- 23. décision de programmation Java ou .Net, db ou pas db
- 24. Insertion en masse de Java dans Oracle
- 25. java insertion de la date dans la base de données
- 26. Insertion de caractères UTF8 dans DB utilisant Django
- 27. Insertion de caractères japonais dans Sybase db à partir d'Excel
- 28. Insertion d'enregistrements dans Sqlite DB à l'aide d'ADO.NET Entity Framework?
- 29. Java DB/Apache Derby avec Android
- 30. Comment puis-je voir combien de clés sont dans une Berkeley DB (Perl)?
J'ai vu ça. Cependant, il s'agit plus d'une FAQ que d'un exemple de code. – mrbombastic
Je viens d'ajouter un exemple de code pour créer un db –
Yup je l'ai eu aussi loin. Comment fonctionne l'insertion d'enregistrements? J'ai déjà une carte de paires clé-valeur. Il y a une notion d'objets Transaction et DatabaseEntry quand je mets dans la base de données. – mrbombastic