1 package search.db;
2 
3 import java.io.IOException;
4 import java.sql.SQLException;
5 
6 import resource.ResourceLocator;
7 import util.ConnectionUtil;
8 import util.TableOperations;
9 import chemaxon.formats.MolExporter;
10import chemaxon.formats.MolFormatException;
11import chemaxon.formats.MolImporter;
12import chemaxon.jchem.db.Importer;
13import chemaxon.jchem.db.TransferException;
14import chemaxon.struc.Molecule;
15import chemaxon.util.ConnectionHandler;
16
17/**
18 * Example code for importing molecules into database.
19 * 
20 * @author JChem Base team, ChemAxon Ltd.
21 */
22public final class DatabaseImportExample {
23
24    private static final String IMPORT_TABLE = "import_test";
25    private ConnectionHandler connHandler;
26
27    public static void main(String[] args) {
28        try {
29            new DatabaseImportExample().run();
30        } catch (Exception e) {
31            e.printStackTrace();
32        }
33    }
34
35    private void run() throws Exception {
36        connHandler = ConnectionUtil.connectToDB();
37        try {
38            createMoleculeTableInDB();
39            listMoleculesToConsole();
40            importMoleculesIntoDB();
41        } finally {
42            ConnectionUtil.closeConnection(connHandler);
43        }
44    }
45
46    private void createMoleculeTableInDB() throws SQLException {
47        TableOperations.createMoleculeTable(connHandler, IMPORT_TABLE);
48    }
49
50    /**
51     * Lists all molecules found in an input file.
52     */
53    private void listMoleculesToConsole() throws IOException, MolFormatException {
54        MolImporter mi = new MolImporter(ResourceLocator.getDefaultInputPath());
55        try {
56            int molCount = 0;
57            Molecule mol = mi.read();
58            while (mol != null) {
59                molCount++;
60                System.out.printf("Molecule %4d: %s\n", molCount,
61                        MolExporter.exportToFormat(mol, "smiles"));
62                mol = mi.read();
63            }
64        } finally {
65            mi.close();
66        }
67    }
68
69    /**
70     * Loads all molecules found in an input file
71     * 
72     * @param ch connection handler to use
73     */
74    private void importMoleculesIntoDB() throws TransferException {
75        System.out.println("\n\nDatabase import:");
76        Importer importer = new Importer();
77
78        importer.setConnectionHandler(connHandler);
79        importer.setTableName(IMPORT_TABLE);
80        importer.setInput(ResourceLocator.getDefaultInputPath());
81        importer.init();
82        int importedMoleculeCount = importer.importMols();
83
84        System.out.printf("%d structures imported\n", importedMoleculeCount);
85    }
86
87}
88