Low Level Database Access: Difference between revisions
Jump to navigation
Jump to search
Content deleted Content added
imported>Hendrik Brummermann No edit summary |
imported>Hendrik Brummermann No edit summary |
||
| (32 intermediate revisions by 2 users not shown) | |||
| Line 1: | Line 1: | ||
{{Navigation for Marauroa Top}} |
{{Navigation for Marauroa Top|Internals}} |
||
{{Navigation for Marauroa Developers}} |
{{Navigation for Marauroa Developers}} |
||
| Line 23: | Line 23: | ||
== Writing your own DAO == |
== Writing your own DAO == |
||
Please stick to the following rules when writing your own DAO classes |
|||
* use <nowiki>[variables]</nowiki> for untrusted data because it will be escaped automatically to prevent SQL Injection Attacks |
|||
* register your class in DAORegistry (see next section) instead of calling the constructor directly |
|||
* use dbTransaction.getLastInsertId() instead of "select @@identity" and call it directly after the insert in question |
|||
* try to avoid database system specific code (pay special attention to generally supported SQL functions) |
|||
* provide all methods with two signatures: One with DBTransaction as first parameter and one without. The second one should just get the transaction itself, call the first one, and commit/rollback the transaction |
|||
== Extending a provided DAO == |
== Extending a provided DAO == |
||
| Line 49: | Line 56: | ||
== Updating the database structure == |
== Updating the database structure == |
||
If you add tables and columns it is a good practice to create them automatically on server start. The method runSQLScript() in the class JDBCHelper can be used to execute an SQL script. Note: You should use "create table if not exists" in stead of simple "create table" so that you can execute the script on every server start without having to worry about whether the table already exists or not. |
|||
Unfortunately there is no "create column if not exists" clause in SQL. So if we have the need to add columns to existing tables, we will need to do the check ourselves. |
|||
The following example shows the code that was used to add the new result column to the passwordChange table. Before that column was added, only successful password changes were logged. So the result column should be initialized to 1. |
|||
<source lang="java"> |
|||
if (!transaction.doesColumnExist("passwordChange", "result")) { |
|||
transaction.execute("ALTER TABLE passwordChange ADD COLUMN (result TINYINT);", null); |
|||
transaction.execute("UPDATE passwordChange SET result=1 WHERE result IS NULL", null); |
|||
} |
|||
</source> |
|||
{{#breadcrumbs: [[Marauroa]] | [[Navigation for Marauroa Developers|Internals]] | [[Low Level Database Access|Low Level Database Access]] }} |
|||