|
| 1 | +/*---------------------------------------------------------------------- |
| 2 | +
|
| 3 | +Example.js |
| 4 | +
|
| 5 | +Demonstrate how to perform a database insert and query with Node.js in |
| 6 | +Oracle Database Cloud services such as Exadata Express, Autonomous |
| 7 | +Transaction Processing, Autonomous Data Warehouse, and others. |
| 8 | +
|
| 9 | +Before running this script: |
| 10 | + - Install Node.js and node-oracledb |
| 11 | + - Install Oracle Instant Client |
| 12 | + - Download and install the cloud service wallet |
| 13 | + - Modify the connect() call below to use the credentials for your database. |
| 14 | +See your cloud service's documentation for details. |
| 15 | +
|
| 16 | +----------------------------------------------------------------------*/ |
| 17 | + |
| 18 | +var oracledb = require('oracledb'); |
| 19 | + |
| 20 | +async function run() { |
| 21 | + let connection; |
| 22 | + |
| 23 | + try { |
| 24 | + |
| 25 | + let sql, binds, options, result; |
| 26 | + |
| 27 | + connection = await oracledb.getConnection( { |
| 28 | + user : 'username', |
| 29 | + password : 'password', |
| 30 | + connectString : 'connect_string' |
| 31 | + }); |
| 32 | + |
| 33 | + // Create a table |
| 34 | + |
| 35 | + await connection.execute( |
| 36 | + `BEGIN |
| 37 | + EXECUTE IMMEDIATE 'DROP TABLE mycloudtab'; |
| 38 | + EXCEPTION |
| 39 | + WHEN OTHERS THEN |
| 40 | + IF SQLCODE NOT IN (-00942) THEN |
| 41 | + RAISE; |
| 42 | + END IF; |
| 43 | + END;`); |
| 44 | + |
| 45 | + await connection.execute( |
| 46 | + `CREATE TABLE mycloudtab (id NUMBER, data VARCHAR2(20))`); |
| 47 | + |
| 48 | + // Insert some data |
| 49 | + |
| 50 | + sql = `INSERT INTO mycloudtab VALUES (:1, :2)`; |
| 51 | + binds = [ [101, "Alpha" ], [102, "Beta" ], [103, "Gamma" ] ]; |
| 52 | + options = { |
| 53 | + autoCommit: true, |
| 54 | + bindDefs: [ |
| 55 | + { type: oracledb.NUMBER }, |
| 56 | + { type: oracledb.STRING, maxSize: 20 } |
| 57 | + ] |
| 58 | + }; |
| 59 | + |
| 60 | + await connection.executeMany(sql, binds, options); |
| 61 | + |
| 62 | + // Query the data |
| 63 | + |
| 64 | + sql = `SELECT * FROM mycloudtab`; |
| 65 | + binds = {}; |
| 66 | + options = {}; |
| 67 | + |
| 68 | + result = await connection.execute(sql, binds, options); |
| 69 | + console.log(result.rows); |
| 70 | + |
| 71 | + } catch (err) { |
| 72 | + console.error(err); |
| 73 | + } finally { |
| 74 | + if (connection) { |
| 75 | + try { |
| 76 | + await connection.close(); |
| 77 | + } catch (err) { |
| 78 | + console.error(err); |
| 79 | + } |
| 80 | + } |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +run(); |
0 commit comments