|
| 1 | +// deno-lint-ignore-file no-explicit-any |
| 2 | + |
| 3 | +const db = new Database(":memory:"); |
| 4 | + |
| 5 | +try { |
| 6 | + // Create sample tables |
| 7 | + db.exec(` |
| 8 | + CREATE TABLE users ( |
| 9 | + id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 10 | + name TEXT NOT NULL, |
| 11 | + age INTEGER, |
| 12 | + email TEXT |
| 13 | + ); |
| 14 | + |
| 15 | + CREATE TABLE products ( |
| 16 | + id INTEGER PRIMARY KEY, |
| 17 | + name TEXT, |
| 18 | + price REAL, |
| 19 | + in_stock INTEGER |
| 20 | + ); |
| 21 | + `); |
| 22 | + |
| 23 | + // Insert with parameters |
| 24 | + const insertUserStmt = db.prepare( |
| 25 | + "INSERT INTO users (name, age, email) VALUES (?, ?, ?)", |
| 26 | + ); |
| 27 | + insertUserStmt.run("Alice Smith", 25, "alice@example.com"); |
| 28 | + insertUserStmt.run("Bob Johnson", 30, "bob@example.com"); |
| 29 | + insertUserStmt.run("Charlie Brown", 28, "charlie@example.com"); |
| 30 | + |
| 31 | + // Select with parameters |
| 32 | + const usersOver26 = db.prepare("SELECT * FROM users WHERE age > ?").all(26); |
| 33 | + console.log("Users over 26:"); |
| 34 | + usersOver26.forEach((user: any) => { |
| 35 | + console.log(`${user.name} (${user.age}): ${user.email}`); |
| 36 | + }); |
| 37 | + |
| 38 | + // Update with parameters |
| 39 | + db.prepare("UPDATE users SET age = ? WHERE name = ?").run( |
| 40 | + 26, |
| 41 | + "Alice Smith", |
| 42 | + ); |
| 43 | + |
| 44 | + // Complex query with multiple parameters |
| 45 | + const filteredUsers = db.prepare( |
| 46 | + "SELECT * FROM users WHERE age BETWEEN ? AND ? AND name LIKE ?", |
| 47 | + ).all(25, 30, "%o%"); |
| 48 | + console.log("\nUsers aged 25-30 with 'o' in name:"); |
| 49 | + filteredUsers.forEach((user: any) => { |
| 50 | + console.log(`${user.name} (${user.age})`); |
| 51 | + }); |
| 52 | + |
| 53 | + // Different parameter types |
| 54 | + const insertProductStmt = db.prepare( |
| 55 | + "INSERT INTO products (id, name, price, in_stock) VALUES (?, ?, ?, ?)", |
| 56 | + ); |
| 57 | + insertProductStmt.run(1, "Laptop", 999.99, true); |
| 58 | + insertProductStmt.run(2, "Mouse", 25.50, false); |
| 59 | + |
| 60 | + db.exec("CREATE TABLE nullable_test (id INTEGER, value TEXT)"); |
| 61 | + const nullStmt = db.prepare( |
| 62 | + "INSERT INTO nullable_test (id, value) VALUES (?, ?)", |
| 63 | + ); |
| 64 | + nullStmt.run(1, "not null"); |
| 65 | + nullStmt.run(2, null); |
| 66 | + |
| 67 | + const nullResults = db.prepare("SELECT * FROM nullable_test").all(); |
| 68 | + console.log("\nNULL parameter test results:"); |
| 69 | + nullResults.forEach((row: any) => { |
| 70 | + console.log( |
| 71 | + `ID: ${row.id}, Value: ${row.value === null ? "NULL" : row.value}`, |
| 72 | + ); |
| 73 | + }); |
| 74 | +} catch (error) { |
| 75 | + console.error("Error:", error); |
| 76 | +} finally { |
| 77 | + db.close(); |
| 78 | +} |
0 commit comments