Lesson 13. Persistence: SQL Databases. Victor Matos Cleveland State University
|
|
|
- Bertina Eaton
- 9 years ago
- Views:
Transcription
1 Lesson 13 Persistence: SQL Databases Victor Matos Cleveland State University Portions of this page are reproduced from work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License.
2 Using SQL databases in Andorid Included into the core Android architecture there is an standalone Database Management System (DBMS) called SQLite which can be used to: Create a database, Define SQL tables, indices, queries, views, triggers Insert rows, Delete rows, Change rows, Run queries and Administer a SQLite database file. 13-2
3 Characteristics of SQLite Transactional SQL database engine. Small footprint (less than 400KBytes) Typeless Serverless Zero-configuration The source code for SQLite is in the public domain. According to their website, SQLite is the most widely deployed SQL database engine in the world. Reference:
4 Characteristics of SQLite 1. SQLite implements most of the SQL-92 standard for SQL. 2. It has partial support for triggers and allows complex queries (exceptions include: right/full outer joins, grant/revoke, updatable views). 3. SQLITE does not implement referential integrity constraints through the foreign key constraint model. 4. SQLite uses a relaxed data typing model. 5. Instead of assigning a type to an entire column, types are assigned to individual values (this is similar to the Variant type in Visual Basic). 6. There is no data type checking, therefore it is possible to insert a string into numeric column and so on. Documentation on SQLITE available at GUI tools for SQLITE: SQL Administrator SQL Expert
5 Creating a SQLite database - Method 1 SQLiteDatabase.openDatabase( mydbpath, null, SQLiteDatabase.CREATE_IF_NECESSARY); If the database does not exist then create a new one. Otherwise, open the existing database according to the flags: OPEN_READWRITE, OPEN_READONLY, CREATE_IF_NECESSARY. Parameters path to database file to open and/or create factory an optional factory class that is called to instantiate a cursor when query is called, or null for default flags to control database access mode Returns the newly opened database Throws SQLiteException if the database cannot be opened 13-5
6 Example1: Creating a SQLite database - Method 1 package cis470.matos.sqldatabases; public class MainActivity extends Activity { SQLiteDatabase public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); TextView txtmsg = (TextView) findviewbyid(r.id.txtmsg); // path to the external SD card (something like: /storage/sdcard/...) // String storagepath = Environment.getExternalStorageDirectory().getPath(); // path to internal memory file system (data/data/cis470.matos.databases) File storagepath = getapplication().getfilesdir(); String mydbpath = storagepath + "/" + "myfriends"; txtmsg.settext("db Path: " + mydbpath); try { db = SQLiteDatabase.openDatabase(myDbPath, null, SQLiteDatabase.CREATE_IF_NECESSARY); // here you do something with your database... db.close(); txtmsg.append("\nall done!"); catch (SQLiteException e) { txtmsg.append("\nerror " + e.getmessage()); // oncreate // class 13-6
7 Example1: Creating a SQLite database - Using Memory SQLite Database is stored using Internal Memory Path: /data/data/cis470.matos.sqldatabases/ Where: cis470.matos.sqldatabases is the package s name 13-7
8 Example1: Creating a SQLite database on the SD card Using: SQLiteDatabase db; String SDcardPath = Environment.getExternalStorageDirectory().getPath() + "/myfriends"; db = SQLiteDatabase.openDatabase( SDcardPath, null, SQLiteDatabase.CREATE_IF_NECESSARY ); Manifest must include: <uses-permission android:name= "android.permission.write_external_storage" /> <uses-permission android:name= "android.permission.read_external_storage" /> 13-8
9 Sharing Limitations Warning Databases created in the internal /data/data/package space are private to that package. You cannot access internal databases belonging to other people (instead use Content Providers or external SD resident DBs). SD stored databases are public. Access to an SD resident database requires the Manifest to include permissions: <uses-permission android:name="android.permission.write_external_storage" /> <uses-permission android:name="android.permission.read_external_storage" /> NOTE: SQLITE (as well as most DBMSs) is not case sensitive. 13-9
10 An Alternative Method: openorcreatedatabase An alternative way of opening/creating a SQLITE database in your local Android s internal data space is given below SQLiteDatabase db = this.openorcreatedatabase( "myfriendsdb", MODE_PRIVATE, null); Assume this app is made in a namespace called cis470.matos.sqldatabases, then the full name of the newly created database file will be: /data/data/cis470.matos.sqldatabases/myfriendsdb Internal Memory Package name DB name The file can be accessed by all components of the same application. Other MODE values: MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE were deprecated on API Level 17. null refers to optional factory class parameter (skip for now) 13-10
11 Type of SQL Commands Once created, the SQLite database is ready for normal operations such as: creating, altering, dropping resources (tables, indices, triggers, views, queries etc.) or administrating database resources (containers, users, ). Action queries and Retrieval queries represent the most common operations against the database. A retrieval query is typically a SQL-Select command in which a table holding a number of fields and rows is produced as an answer to a data request. An action query usually performs maintenance and administrative tasks such as manipulating tables, users, environment, etc
12 Transaction Processing Transactions are desirable because they help maintaining consistent data and prevent unwanted data losses due to abnormal termination of execution. In general it is convenient to process action queries inside the protective frame of a database transaction in which the policy of complete success or total failure is transparently enforced. This notion is called: atomicity to reflect that all parts of a method are fused in an indivisible statement
13 Transaction Processing The typical Android s way of running transactions on a SQLiteDatabase is illustrated by the following code fragment (Assume db is a SQLiteDatabase) db.begintransaction(); try { //perform your database operations here... db.settransactionsuccessful(); //commit your changes catch (SQLiteException e) { //report problem finally { db.endtransaction(); The transaction is defined between the methods: begintransaction and endtransaction. You need to issue the settransactionsuccessful()call to commit any changes. The absence of it provokes an implicit rollback operation; consequently the database is reset to the state previous to the beginning of the transaction 13-13
14 Create and Populate a SQL Table The SQL syntax used for creating and populating a table is illustrated in the following examples create table tblamigo ( recid integer PRIMARY KEY autoincrement, name text, phone text ); insert into tblamigo(name, phone) values ('AAA', ' ' ); The autoincrement value for recid is NOT supplied in the insert statement as it is internally assigned by the DBMS
15 Example 2. Create and Populate a SQL Table Our Android app will use the execsql( ) method to manipulate SQL action queries. The example below creates a new table called tblamigo. The table has three fields: a numeric unique identifier called recid, and two string fields representing our friend s name and phone. If a table with such a name exists it is first dropped and then created again. Finally three rows are inserted in the table. Note: For presentation economy we do not show the entire code which should include a transaction frame. db.execsql("create table tblamigo (" + " recid integer PRIMARY KEY autoincrement, " + " name text, " + " phone text ); " ); db.execsql( "insert into tblamigo(name, phone) values ('AAA', ' ');" ); db.execsql( "insert into tblamigo(name, phone) values ('BBB', ' ');" ); db.execsql( "insert into tblamigo(name, phone) values ('CCC', ' ');" ); 13-15
16 Example 2. Create and Populate a SQL Table After executing the previous code snippet, we transfered the database to the developer s file system and used the SQL-ADMINISTRATION tool. There we submitted the SQL-Query: select * from tblamigo. Results are shown below
17 Example 2. Create and Populate a SQL Table Comments 1. The field recid is defined as the table s PRIMARY KEY. 2. The autoincrement feature guarantees that each new record will be given a unique serial number (0,1,2, ). 3. On par with other SQL systems, SQLite offers the data types: text, varchar, integer, float, numeric, date, time, timestamp, blob, boolean. 3. In general any well-formed DML SQL action command (insert, delete, update, create, drop, alter, etc.) could be framed inside an execsql(... ) method call. Caution: You should call the execsql method inside of a try-catch-finally block. Be aware of potential SQLiteException conflicts thrown by the method
18 Example 2. Create and Populate a SQL Table User defined fields NOTE: SQLITE uses an invisible field called ROWID to uniquely identify each row in each table. Consequently in our example the field recid and the database ROWID are functionally similar. RowID
19 Asking Questions - SQL Queries 1. Retrieval queries are known as SQL-select statements. 2. Answers produced by retrieval queries are always held in a table. 3. In order to process the resulting table rows, the user should provide a cursor device. Cursors allow a row-atthe-time access mechanism on SQL tables. Android-SQLite offers two strategies for phrasing select statements: rawqueries and simple queries. Both return a database cursor. 1. Raw queries take for input any (syntactically correct) SQL-select statement. The select query could be as complex as needed and involve any number of tables (only a few exceptions such as outer-joins) 2. Simple queries are compact parametized lookup functions that operate on a single table (for developers who prefer not to use SQL)
20 SQL Select Statement Syntax select from field 1, field 2,, field n table 1, table 2,, table n where ( restriction-join-conditions ) order by field n1,, field nm group by field m1,, field mk having (group-condition) The first two lines are mandatory, the rest is optional. 1. The select clause indicates the fields to be included in the answer 2. The from clause lists the tables used in obtaining the answer 3. The where component states the conditions that records must satisfy in order to be included in the output. 4. Order by tells the sorted sequence on which output rows will be presented 5. Group by is used to partition the tables and create sub-groups 6. Having formulates a condition that sub-groups made by partitioning need to satisfy
21 Two Examples of SQL-Select Statements Example A. SELECT FROM WHERE ORDER BY LastName, cellphone ClientTable state = Ohio LastName Example B. SELECT FROM GROUP BY city, count(*) as TotalClients ClientTable city 13-21
22 Example3. Using a Parameterless RawQuery (version 1) Consider the following code fragment Cursor c1 = db.rawquery("select * from tblamigo", null); 1. The previous rawquery contains a select-statement that retrieves all the rows (and all the columns) stored in the table tblamigo. The resulting table is wrapped by a Cursor object c1. 2. The select * clause instructs SQL to grab all-columns held in a row. 3. Cursor c1 will be used to traverse the rows of the resulting table. 4. Fetching a row using cursor c1 requires advancing to the next record in the answer set (cursors are explained a little later in this section). 5. Fields provided by SQL must be bound to local Java variables (soon we will see to that)
23 Example3. Using a Parametized RawQuery (version 2) Passing arguments. Assume we want to count how many friends are there whose name is BBB and their recid > 1. We could use the following solution: String mysql = "select count(*) as Total " + " from tblamigo " + " where recid >? " + " and name =? "; String[] args = {"1", "BBB"; Cursor c1 = db.rawquery(mysql, args); The various symbols? in the SQL statement represent positional placeholders. When.rawQuery() is called, the system binds each empty placeholder? with the supplied args-value. Here the first? will be replaced by 1 and the second by BBB
24 Example3. Using a Stitched RawQuery (version 3) As in the previous example, assume we want to count how many friends are there whose name is BBB and their recid > 1. We could use the following solution: String[] args = {"1", "BBB"; String mysql = " select count(*) as Total " + " from tblamigo " + " where recid > " + args[0] + " and name = '" + args[1] + "'"; Cursor c1 = db.rawquery(mysql, null); Instead of the symbols? acting as placeholder, we conveniently concatenate the necessary data fragments during the assembling of our SQL statement
25 SQL Cursors Cursors are used to gain sequential & random access to tables produced by SQL select statements. Cursors support one row-at-the-time operations on a table. Although in some DBMS systems cursors can be used to update the underlying dataset, the SQLite version of cursors is read-only. Cursors include several types of operators, among them: 1. Positional awareness: isfirst(), islast(), isbeforefirst(), isafterlast(). 2. Record navigation: movetofirst(), movetolast(), movetonext(), movetoprevious(), move(n). 3. Field extraction: getint, getstring, getfloat, getblob, getdouble, etc. 4. Schema inspection: getcolumnname(), getcolumnnames(), getcolumnindex(), getcolumncount(), getcount()
26 Example 4A. Traversing a Cursor Simple Case 1 of String sql = "select * from tblamigo"; Cursor c1 = db.rawquery(sql, null); c1.movetoposition(-1); while ( c1.movetonext() ){ int recid = c1.getint(0); String name = c1.getstring(1); String phone = c1.getstring(c1.getcolumnindex("phone")); // do something with the record here Prepare a rawquery passing a simple sql statement with no arguments, catch the resulting tuples in cursor c1. 2. Move the fetch marker to the absolute position prior to the first row in the file. The valid range of values is -1 <= position <= count. 3. Use movetonext() to visit each row in the result set 13-26
27 Example 4B. Traversing a Cursor Enhanced Navigation 1 of private String showcursor( Cursor cursor) { // reset cursor's top (before first row) cursor.movetoposition(-1); String cursordata = "\ncursor: ["; try { // get SCHEMA (column names & types) String[] colname = cursor.getcolumnnames(); for(int i=0; i<colname.length; i++){ String datatype = getcolumntype(cursor, i); cursordata += colname[i] + datatype; if (i<colname.length-1){ cursordata+= ", "; catch (Exception e) { Log.e( "<<SCHEMA>>", e.getmessage() ); cursordata += "]"; // now get the rows cursor.movetoposition(-1); //reset cursor's top 13-27
28 Example 4B. Traversing a Cursor Enhanced Navigation 2 of while (cursor.movetonext()) { String cursorrow = "\n["; for (int i = 0; i < cursor.getcolumncount(); i++) { cursorrow += cursor.getstring(i); if (i<cursor.getcolumncount()-1) cursorrow += ", "; cursordata += cursorrow + "]"; return cursordata + "\n"; 5 private String getcolumntype(cursor cursor, int i) { try { //peek at a row holding valid data cursor.movetofirst(); int result = cursor.gettype(i); String[] types = {":NULL", ":INT", ":FLOAT", ":STR", ":BLOB", ":UNK" ; //backtrack - reset cursor's top cursor.movetoposition(-1); return types[result]; catch (Exception e) { return " "; 13-28
29 Comments Example 4B Enhanced Navigation 1. The method: showcursor( Cursor cursor ) implements the process of visiting individual rows retrieved by a SQL statement. The argument cursor, is a wrapper around the SQL resultset. For example, you may assume cursor was created using a statement such as: Cursor cursor = db.rawquery("select * from tblamigo", null); 2. The database schema for tblamigo consists of the attributes: recid, name, and phone. The method getcolumnnames() provides the schema. 3. The method movetonext forces the cursor to travel from its current position to the next available row. 4. The accessor.getstring is used as a convenient way of extracting SQL fields without paying much attention to the actual data type of the fields. 5. The function.getcolumntype() provides the data type of the current field (0:null, 1:int, 2:float, 3:string, 4:blob) 13-29
30 SQLite Simple Queries - Template Based Queries Simple SQLite queries use a template oriented schema whose goal is to help non-sql developers in their process of querying a database. This template exposes all the components of a basic SQL-select statement. Simple queries can only retrieve data from a single table. The method s signature has a fixed sequence of seven arguments representing: 1. the table name, 2. the columns to be retrieved, 3. the search condition (where-clause), 4. arguments for the where-clause, 5. the group-by clause, 6. having-clause, and 7. the order-by clause
31 SQLite Simple Queries - Template Based Queries The signature of the SQLite simple.query method is: db.query ( String table, String[] columns, String selection, String[] selectionargs, String groupby, String having, String orderby ) 13-31
32 Example5. SQLite Simple Queries Assume we need to consult an EmployeeTable (see next Figure) and find the average salary of female employees supervised by emp Each output row consists of Dept. No, and ladies-average-salary value. Our output should list the highest average first, then the second, and so on. Do not include depts. having less than two employees. String[] columns = {"Dno", "Avg(Salary) as AVG"; String[] conditionargs = {"F", " "; Cursor c = db.query ("EmployeeTable", columns, "sex =? And superssn =? ", conditionargs, "Dno", "Count(*) > 2", "AVG Desc " ); table name ouput columns condition condition-args group by having order by 13-32
33 Example5. SQLite Simple Queries This is a representation of the EmployeeTable used in the previous example. It contains: first name, initial, last name, SSN, birthdate, address, sex, salary, supervisor s SSN, and department number
34 Example6. SQLite Simple Queries In this example we use the tblamigo table. We are interested in selecting the columns: recid, name, and phone. The condition to be met is that RecID must be greater than 2, and names must begin with B and have three or more letters. String [] columns = {"recid", "name", "phone"; Cursor c1 = db.query ( "tblamigo", columns, "recid > 2 and length(name) >= 3 and name like 'B%' ", null, null, null, "recid" ); int recretrieved = c1.getcount(); We enter null in each component not supplied to the method. For instance, in this example select-args, having, and group-by are not used
35 Example7. SQLite Simple Queries In this example we will construct a more complex SQL select statement. We are interested in tallying how many groups of friends whose recid > 3 have the same name. In addition, we want to see name groups having no more than four people each. A possible SQL-select statement for this query would be something like: select name, count(*) as TotalSubGroup from tblamigo where recid > 3 group by name having count(*) <= 4; 13-35
36 Example7. SQLite Simple Queries An equivalent Android-SQLite solution using a simple template query follows String [] selectcolumns = {"name", "count(*) as TotalSubGroup"; String wherecondition = "recid >? "; String [] whereconditionargs = {"3"; String groupby = "name"; String having = "count(*) <= 4"; String orderby = "name"; Cursor cursor = db.query ( "tblamigo", selectcolumns, wherecondition, whereconditionargs, groupby, having, orederby ); 13-36
37 Example7. SQLite Simple Queries Observations 1. The selectcolumns string array contains the output fields. One of them (name) is already part of the table, while TotalSubGroup is an alias for the computed count of each name sub-group. 2. The symbol? in the wherecondition is a place-marker for a substitution. The value 3 taken from the whereconditionargs is to be injected there. 3. The groupby clause uses name as a key to create sub-groups of rows with the same name value. The having clause makes sure we only choose subgroups no larger than four people
38 SQL Action Queries Action queries are the SQL way of performing maintenance operations on tables and database resources. Example of action-queries include: insert, delete, update, create table, drop, etc. Examples: insert into tblamigos values ( Macarena, ); update tblamigos set name = Maria Macarena where phone = ; delete from tblamigos where phone = ; create table Temp ( column1 int, column2 text, column3 date ); drop table Temp; 13-38
39 SQLite Action Queries Using: ExecSQL Perhaps the simplest Android way to phrase a SQL action query is to stitch together the pieces of the SQL statement and give it to the easy to use but rather limited- execsql( ) method. Unfortunately SQLite execsql does NOT return any data. Therefore knowing how many records were affected by the action is not possible with this operator. Instead you should use the Android versions describe in the next section. db.execsql( "update tblamigo set name = (name 'XXX') where phone >= ' ' "); This statement appends XXX to the name of those whose phone number is equal or greater than Note The symbol is the SQL concatenate operator 13-39
40 SQLite Action Queries Using: ExecSQL cont. 1 Alternatively, the SQL action-statement used in ExecSQL could be pasted from pieces as follows: String thevalue = " "; db.execsql( "update tblamigo set name = (name 'XXX') " + " where phone >= '" + thevalue + "' " ); The same strategy could be applied to other SQL action-statements such as: delete from where, insert into.values, etc
41 Android s INSERT, DELETE, UPDATE Operators Android provides a number of additional methods to perform insert, delete, update operations. They all return some feedback data such as the record ID of a recently inserted row, or number of records affected by the action. This format is recommended as a better alternative than execsql. public long insert(string table, String nullcolumnhack, ContentValues values ) public int update( String table, ContentValues values, String whereclause, String[] whereargs ) public int delete( String table, String whereclause, String[] whereargs) 13-41
42 ContentValues Class This class is used to store a set of [name, value] pairs (functionally equivalent to Bundles). When used in combination with SQLite, a ContentValues object is just a convenient way of passing a variable number of parameters to the SQLite action functions. Like bundles, this class supports a group of put/get methods to move data in/out of the container. ContentValues myargs= new ContentValues(); myargs.put("name", "ABC"); myargs.put("phone", " "); myargs Key Value name ABC phone
43 Android s INSERT Operation public long insert(string table, String nullcolumnhack, ContentValues values) The method tries to insert a row in a table. The row s column-values are supplied in the map called values. If successful, the method returns the rowid given to the new record, otherwise -1 is sent back. Parameters table the table on which data is to be inserted nullcolumnhack Empty and Null are different things. For instance, values could be defined but empty. If the row to be inserted is empty (as in our next example) this column will explicitly be assigned a NULL value (which is OK for the insertion to proceed). values Similar to a bundle (name, value) containing the column values for the row that is to be inserted
44 Android s INSERT Operation ContentValues rowvalues= new ContentValues(); rowvalues.put("name", "ABC"); rowvalues.put("phone", " "); long rowposition = db.insert("tblamigo", null, rowvalues); rowvalues.put("name", "DEF"); rowvalues.put("phone", " "); rowposition = db.insert("tblamigo", null, rowvalues); rowvalues.clear(); rowposition = db.insert("tblamigo", null, rowvalues); rowposition = db.insert("tblamigo", "name", rowvalues); 13-44
45 Android s INSERT Operation Comments 1. A set of <key, values> called rowvalues is creted and supplied to the insert() method to be added to tblamigo. Each tblamigo row consists of the columns: recid, name, phone. Remember that recid is an autoincremented field, its actual value is to be determined later by the database when the record is accepted. 2. The newly inserted record returns its rowid (4 in this example) 3. A second records is assembled and sent to the insert() method for insertion in tblamigo. After it is collocated, it returns its rowid (5 in this example). 4. The rowvalues map is reset, therefore rowvalues which is not null becomes empty. 5. SQLite rejects attempts to insert an empty record returning rowid The second argument identifies a column in the database that allows NULL values (NAME in this case). Now SQL purposely inserts a NULL value on that column (as well as in other fields, except the key RecId) and the insertion successfully completes
46 Android s UPDATE Operation public int update ( String table, ContentValues values, String whereclause, String[] whereargs ) The method tries to update row(s) in a table. The SQL set column=newvalue clause is supplied in the values map in the form of [key,value] pairs. The method returns the number of records affected by the action. Parameters table the table on which data is to be updated values whereclause Similar to a bundle (name, value) containing the columnname and NewValue for the fields in a row that need to be updated. This is the condition identifying the rows to be updated. For instance name =? where? Is a placeholder. Passing null updates the entire table. whereargs Data to replace? placeholders defined in the whereclause
47 Android s UPDATE Operation Example We want to use the.update() method to express the following SQL statement: Update tblamigo set name = maria where (recid > 2 and recid < 7) 1 Here are the steps to make the call using Android s equivalent Update Method String [] whereargs = {"2", "7"; ContentValues updvalues = new ContentValues(); 2 3 updvalues.put("name", "Maria"); int recaffected = db.update( "tblamigo", updvalues, "recid >? and recid <?", whereargs ); 13-47
48 Android s UPDATE Operation Comments 1. Our whereargs is an array of arguments. Those actual values will replace the placeholders? set in the whereclause. 2. The map updvalues is defined and populated. In our case, once a record is selected for modifications, its name field will changed to the new value maria. 3. The db.update() method attempts to update all records in the given table that satisfy the filtering condition set by the whereclause. After completion it returns the number of records affected by the update (0 If it fails). 4. The update filter verifies that "recid >? and recid <? ". After the args substitutions are made the new filter becomes: "recid > 2 and recid < 7"
49 Android s DELETE Operation public int delete ( String table, String whereclause, String[] whereargs ) The method is called to delete rows in a table. A filtering condition and its arguments are supplied in the call. The condition identifies the rows to be deleted. The method returns the number of records affected by the action. Parameters table the table on which data is to be deleted whereclause This is the condition identifying the records to be deleted. For instance name =? where? Is a placeholder. Passing null deletes all the rows in the table. whereargs Data to replace? placeholders defined in the whereclause
50 Android s DELETE Operation Example Consider the following SQL statement: Delete from tblamigo wehere recid > 2 and recid < 7 An equivalent implementation using the Androi d delete method follows: String [] whereargs = {"2", "7"; int recaffected = db.delete( "tblamigo", "recid >? and recid <?", whereargs); A record should be deleted if its recid is in between the values 2, and 7. The actual values are taken from the whereargs array. The method returns the number of rows removed after executing the command (or 0 if none)
51 Database Visibility 1. Any Application can access a database externally stored in the device s SD. All it s needed is knowledge of the path where the database file is located (arguable, this is an opened door to security problems). 2. Databases created privately inside the application s process space cannot be shared (however they consume precious memory resources) App-1 SD card Database1 Database2 App-3 App-4 3. Other ways of sharing data will be explored later (ContentProvider). App-2 Private Memory Database
52 Database Visibility Emulator s File Explorer showing the location of a private database The path to the private memory database is: data/data/cis470.matos.databases/myfriendsdb 13-52
53 Using GUI Tools for SQLite In order to move a copy of the database in and out of the Emulator s storage space and either receive or send the file into/from the local computer s file system you may use the commands: adb pull <full_path_to_database> and adb push <full_path_to_database>. You may also use the Eclipse s DDMS Perspective to push/pull files in/out the emulator s file system. Once the database is in your computer s disk you may manipulate the database using a userfriendly tool such as: SQLite Administrator ( SQLite Manager (Firefox adds-on) 13-53
54 Complete Code for Examples 2-7 XML Layout <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="4dp" android:orientation="vertical" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#ff0000ff" android:text="sqldemo2. Android Databases" android:textcolor="#ffffffff" android:textsize="20dp" android:textstyle="bold" /> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="" /> </ScrollView> </LinearLayout> 13-54
55 public class SQLDemo2 extends Activity { SQLiteDatabase db; TextView txtmsg; SQL Databases Complete Code for Examples public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); txtmsg = (TextView) findviewbyid(r.id.txtmsg); SQLDemo2.java try { opendatabase(); // open (create if needed) database droptable(); // if needed drop table tblamigos insertsomedbdata(); // create-populate tblamigos userawqueryshowall(); // display all records userawquery1(); // fixed SQL with no arguments userawquery2(); // parameter substitution userawquery3(); //manual string concatenation usesimplequery1(); //simple (parametric) query usesimplequery2(); //nontrivial 'simple query' showtable("tblamigo"); //retrieve all rows from a table updatedb(); //use execsql to update useinsertmethod(); //use insert method useupdatemethod(); //use update method usedeletemethod(); //use delete method db.close(); // make sure to release the DB txtmsg.append("\nall Done!"); 13-55
56 Complete Code for Examples 2-7 SQLDemo2.java cont. 1 catch (Exception e) { txtmsg.append("\nerror oncreate: " + e.getmessage()); finish(); // oncreate // ///////////////////////////////////////////////////////////////////////////// private void opendatabase() { try { // path to the external SD card (something like: /storage/sdcard/...) // String storagepath = Environment.getExternalStorageDirectory().getPath(); // path to internal memory file system (data/data/cis470.matos.databases) File storagepath = getapplication().getfilesdir(); String mydbpath = storagepath + "/" + "myfriends"; txtmsg.settext("db Path: " + mydbpath); db = SQLiteDatabase.openDatabase(myDbPath, null, SQLiteDatabase.CREATE_IF_NECESSARY); txtmsg.append("\n-opendatabase - DB was opened"); catch (SQLiteException e) { txtmsg.append("\nerror opendatabase: " + e.getmessage()); finish(); // opendatabase 13-56
57 Complete Code for Examples 2-7 SQLDemo2.java cont. 2 private void insertsomedbdata() { // create table: tblamigo db.begintransaction(); try { // create table db.execsql("create table tblamigo (" + " recid integer PRIMARY KEY autoincrement, " + " name text, " + " phone text ); "); // commit your changes db.settransactionsuccessful(); txtmsg.append("\n-insertsomedbdata - Table was created"); catch (SQLException e1) { txtmsg.append("\nerror insertsomedbdata: " + e1.getmessage()); finish(); finally { db.endtransaction(); // populate table: tblamigo db.begintransaction(); try { // insert rows db.execsql("insert into tblamigo(name, phone) " + " values ('AAA', ' ' );"); 13-57
58 Complete Code for Examples 2-7 SQLDemo2.java cont. 3 db.execsql("insert into tblamigo(name, phone) " + " values ('BBB', ' ' );"); db.execsql("insert into tblamigo(name, phone) " + " values ('CCC', ' ' );"); // commit your changes db.settransactionsuccessful(); txtmsg.append("\n-insertsomedbdata - 3 rec. were inserted"); catch (SQLiteException e2) { txtmsg.append("\nerror insertsomedbdata: " + e2.getmessage()); finally { db.endtransaction(); // insertsomedata // /////////////////////////////////////////////////////////////// private void userawqueryshowall() { try { // hard-coded SQL select with no arguments String mysql = "select * from tblamigo"; Cursor c1 = db.rawquery(mysql, null); txtmsg.append("\n-userawqueryshowall" + showcursor(c1) ); 13-58
59 Complete Code for Examples 2-7 SQLDemo2.java cont. 4 catch (Exception e) { txtmsg.append("\nerror userawquery1: " + e.getmessage()); // userawquery1 // /////////////////////////////////////////////////////////// private String showcursor( Cursor cursor) { // show SCHEMA (column names & types) cursor.movetoposition(-1); //reset cursor's top String cursordata = "\ncursor: ["; try { // get column names String[] colname = cursor.getcolumnnames(); for(int i=0; i<colname.length; i++){ String datatype = getcolumntype(cursor, i); cursordata += colname[i] + datatype; if (i<colname.length-1){ cursordata+= ", "; catch (Exception e) { Log.e( "<<SCHEMA>>", e.getmessage() ); cursordata += "] ; 13-59
60 Complete Code for Examples 2-7 SQLDemo2.java cont. 5 // now get the rows cursor.movetoposition(-1); //reset cursor's top while (cursor.movetonext()) { String cursorrow = "\n["; for (int i = 0; i < cursor.getcolumncount(); i++) { cursorrow += cursor.getstring(i); if (i<cursor.getcolumncount()-1) cursorrow += ", "; cursordata += cursorrow + "]"; return cursordata + "\n"; // /////////////////////////////////////////////////////////////////////////// private String getcolumntype(cursor cursor, int i) { try { //peek at a row holding valid data cursor.movetofirst(); int result = cursor.gettype(i); String[] types = {":NULL", ":INT", ":FLOAT", ":STR", ":BLOB", ":UNK" ; //backtrack - reset cursor's top cursor.movetoposition(-1); return types[result]; catch (Exception e) { return " "; 13-60
61 Complete Code for Examples 2-7 SQLDemo2.java cont. 6 private void userawquery1() { try { // hard-coded SQL select with no arguments String mysql = "select * from tblamigo"; Cursor c1 = db.rawquery(mysql, null); // get the first recid c1.movetofirst(); int index = c1.getcolumnindex("recid"); int therecid = c1.getint(index); txtmsg.append("\n-userawquery1 - first recid " + therecid); txtmsg.append("\n-userawquery1" + showcursor(c1) ); catch (Exception e) { txtmsg.append("\nerror userawquery1: " + e.getmessage()); // userawquery1 // /////////////////////////////////////////////////////////////// private void userawquery2() { try { // use:? as argument's placeholder String mysql = " select recid, name, phone " + " from tblamigo " + " where recid >? " + " and name =? "; String[] args = { "1", "BBB" ; 13-61
62 Complete Code for Examples 2-7 SQLDemo2.java cont. 7 Cursor c1 = db.rawquery(mysql, args); // pick NAME from first returned row c1.movetofirst(); int index = c1.getcolumnindex("name"); String thename = c1.getstring(index); txtmsg.append("\n-userawquery2 Retrieved name: " + thename); txtmsg.append("\n-userawquery2 " + showcursor(c1) ); catch (Exception e) { txtmsg.append("\nerror userawquery2: " + e.getmessage()); // userawquery2 // /////////////////////////////////////////////////////////////// private void userawquery3() { try { // arguments injected by manual string concatenation String[] args = { "1", "BBB" ; String mysql = " select recid, name, phone" + " from tblamigo " + " where recid > " + args[0] + " and name = '" + args[1] + "'"; Cursor c1 = db.rawquery(mysql, null); 13-62
63 Complete Code for Examples 2-7 SQLDemo2.java cont. 8 // pick PHONE from first returned row int index = c1.getcolumnindex("phone"); //case sensitive c1.movetonext(); String thephone = c1.getstring(index); txtmsg.append("\n-userawquery3 - Phone: " + thephone); txtmsg.append("\n-userawquery3 " + showcursor(c1) ); catch (Exception e) { txtmsg.append("\nerror userawquery3: " + e.getmessage()); // userawquery3 // /////////////////////////////////////////////////////////////// private void usesimplequery1() { try { // simple-parametric query on one table. // arguments: tablename, columns, condition, cond-args, // groupbycol, havingcond, orderby // the next parametric query is equivalent to SQL stmt: // select recid, name, phone from tblamigo // where recid > 1 and length(name) >= 3 // order by recid 13-63
64 Complete Code for Examples 2-7 SQLDemo2.java cont. 9 Cursor c1 = db.query( "tblamigo", new String[] { "recid", "name", "phone", "recid > 1 and length(name) >= 3 ", null, null, null, "recid"); // get NAME from first data row int index = c1.getcolumnindex("phone"); c1.movetofirst(); String thename = c1.getstring(index); txtmsg.append("\n-usesimplequery1 - Total rec " + thename); txtmsg.append("\n-usesimplequery1 " + showcursor(c1) ); catch (Exception e) { txtmsg.append("\nerror usesimplequery1: " + e.getmessage()); // usesimplequery
65 Complete Code for Examples 2-7 SQLDemo2.java cont. 10 private void usesimplequery2() { try { // nontrivial 'simple query' on one table String[] selectcolumns = { "name", "count(*) as TotalSubGroup" ; String wherecondition = "recid >=?"; String[] whereconditionargs = { "1" ; String groupby = "name"; String having = "count(*) <= 4"; String orderby = "name"; Cursor c1 = db.query("tblamigo", selectcolumns, wherecondition, whereconditionargs, groupby, having, orderby); int thetotalrows = c1.getcount(); txtmsg.append("\n-usesimplequery2 - Total rec: " + thetotalrows); txtmsg.append("\n-usesimplequery2 " + showcursor(c1) ); catch (Exception e) { txtmsg.append("\nerror usesimplequery2: " + e.getmessage()); // usesimplequery
66 Complete Code for Examples 2-7 SQLDemo2.java cont. 11 private void showtable(string tablename) { try { String sql = "select * from " + tablename ; Cursor c = db.rawquery(sql, null); txtmsg.append("\n-showtable: " + tablename + showcursor(c) ); catch (Exception e) { txtmsg.append("\nerror showtable: " + e.getmessage()); // usecursor1 // /////////////////////////////////////////////////////////////// private void usecursor1() { try { // this is similar to showcursor(...) // obtain a list of records[recid, name, phone] from DB String[] columns = { "recid", "name", "phone" ; // using simple parametric cursor Cursor c = db.query("tblamigo", columns, null, null, null, null, "recid"); int thetotal = c.getcount(); txtmsg.append("\n-usecursor1 - Total rec " + thetotal); txtmsg.append("\n"); int idcol = c.getcolumnindex("recid"); int namecol = c.getcolumnindex("name"); int phonecol = c.getcolumnindex("phone"); 13-66
67 Complete Code for Examples 2-7 SQLDemo2.java cont. 12 c.movetoposition(-1); while (c.movetonext()) { columns[0] = Integer.toString((c.getInt(idCol))); columns[1] = c.getstring(namecol); columns[2] = c.getstring(phonecol); txtmsg.append(columns[0] + " " + columns[1] + " " + columns[2] + "\n"); catch (Exception e) { txtmsg.append("\nerror usecursor1: " + e.getmessage()); finish(); // usecursor1 // /////////////////////////////////////////////////////////////////// private void updatedb() { // action query performed using execsql // add 'XXX' to the name of person whose phone is txtmsg.append("\n-updatedb"); try { String thephoneno = " "; db.execsql(" update tblamigo set name = (name 'XXX') " + " where phone = '" + thephoneno + "' "); showtable("tblamigo"); 13-67
68 Complete Code for Examples 2-7 SQLDemo2.java cont. 13 catch (Exception e) { txtmsg.append("\nerror updatedb: " + e.getmessage()); usecursor1(); // /////////////////////////////////////////////////////////////////// private void droptable() { // (clean start) action query to drop table try { db.execsql(" drop table tblamigo; "); // >>Toast.makeText(this, "Table dropped", 1).show(); txtmsg.append("\n-droptable - dropped!!"); catch (Exception e) { txtmsg.append("\nerror droptable: " + e.getmessage()); finish(); // ////////////////////////////////////////////////////////////////// public void useinsertmethod() { // an alternative to SQL "insert into table values(...)" // ContentValues is an Android dynamic row-like container try { ContentValues initialvalues = new ContentValues(); initialvalues.put("name", "ABC"); initialvalues.put("phone", " "); int rowposition = (int) db.insert("tblamigo", null, initialvalues); 13-68
69 Complete Code for Examples 2-7 SQLDemo2.java cont. 14 txtmsg.append("\n-useinsertmethod rec added at: " + rowposition); showtable("tblamigo"); catch (Exception e) { txtmsg.append("\n-useinsertmethod - Error: " + e.getmessage()); // useinsertmethod // /////////////////////////////////////////////////////////////////// private void useupdatemethod() { try { // using the 'update' method to change name of selected friend String[] whereargs = { "1" ; ContentValues updvalues = new ContentValues(); updvalues.put("name", "Maria"); int recaffected = db.update("tblamigo", updvalues, "recid =? ", whereargs); txtmsg.append("\n-useupdatemethod - Rec Affected " + recaffected); showtable("tblamigo"); catch (Exception e) { txtmsg.append("\n-useupdatemethod - Error: " + e.getmessage() ); 13-69
70 Complete Code for Examples 2-7 SQLDemo2.java cont. 15 private void usedeletemethod() { // using the 'delete' method to remove a group of friends // whose id# is between 2 and 7 try { String[] whereargs = { "2" ; int recaffected = db.delete("tblamigo", "recid =?", whereargs); txtmsg.append("\n-usedeletemethod - Rec affected " + recaffected); showtable("tblamigo"); catch (Exception e) { txtmsg.append("\n-usedeletemethod - Error: " + e.getmessage()); // class 13-70
71 Questions 13-71
72 Appendix 1: Database Dictionary - SQLITE Master Table You may query the SQLITE master table (named: sqlite_master) looking for a table, index, or other database object. Example select * from sqlite_master; Examination of this field provides the table schema 13-72
73 Appendix 1: Database Dictionary - SQLITE Master Table In Java code you may formulate the test for existence of a database object using something similar to the following fragment public boolean tableexists(sqlitedatabase db, String tablename) { //true if table exists, false otherwise String mysql = " SELECT name FROM sqlite_master " + " WHERE type='table' " + " AND name='" + tablename + "'"; int resultsize = db.rawquery(mysql, null).getcount(); if (resultsize ==0) { return true; else return false; 13-73
74 Appendix 1: Database Dictionary - SQLITE Master Table Appendix 2: Convenient SQL Database Command In Java code you may state the request for CREATE or REPLACE a table using the following safe construct: db.execsql(" DROP TABLE IF EXISTS tblamigo; "); 13-74
Android Persistency: SQL Databases
17 Android Persistency: Victor Matos Cleveland State University Notes are based on: Android Developers http://developer.android.com/index.html 17. Android Using SQL databases in Android. Android (as well
relational database tables row column SQL
SQLite in Android 1 What is a database? relational database: A method of structuring data as tables associated to each other by shared attributes. a table row corresponds to a unit of data called a record;
ANDROID APPS DEVELOPMENT FOR MOBILE GAME
ANDROID APPS DEVELOPMENT FOR MOBILE GAME Lecture 7: Data Storage and Web Services Overview Android provides several options for you to save persistent application data. Storage Option Shared Preferences
SQL Simple Queries. Chapter 3.1 V3.0. Copyright @ Napier University Dr Gordon Russell
SQL Simple Queries Chapter 3.1 V3.0 Copyright @ Napier University Dr Gordon Russell Introduction SQL is the Structured Query Language It is used to interact with the DBMS SQL can Create Schemas in the
How To Create A Table In Sql 2.5.2.2 (Ahem)
Database Systems Unit 5 Database Implementation: SQL Data Definition Language Learning Goals In this unit you will learn how to transfer a logical data model into a physical database, how to extend or
SQL. Short introduction
SQL Short introduction 1 Overview SQL, which stands for Structured Query Language, is used to communicate with a database. Through SQL one can create, manipulate, query and delete tables and contents.
CSC 443 Data Base Management Systems. Basic SQL
CSC 443 Data Base Management Systems Lecture 6 SQL As A Data Definition Language Basic SQL SQL language Considered one of the major reasons for the commercial success of relational databases SQL Structured
database abstraction layer database abstraction layers in PHP Lukas Smith BackendMedia [email protected]
Lukas Smith database abstraction layers in PHP BackendMedia 1 Overview Introduction Motivation PDO extension PEAR::MDB2 Client API SQL syntax SQL concepts Result sets Error handling High level features
Information Systems SQL. Nikolaj Popov
Information Systems SQL Nikolaj Popov Research Institute for Symbolic Computation Johannes Kepler University of Linz, Austria [email protected] Outline SQL Table Creation Populating and Modifying
5. CHANGING STRUCTURE AND DATA
Oracle For Beginners Page : 1 5. CHANGING STRUCTURE AND DATA Altering the structure of a table Dropping a table Manipulating data Transaction Locking Read Consistency Summary Exercises Altering the structure
Database Programming with PL/SQL: Learning Objectives
Database Programming with PL/SQL: Learning Objectives This course covers PL/SQL, a procedural language extension to SQL. Through an innovative project-based approach, students learn procedural logic constructs
TUTORIAL. BUILDING A SIMPLE MAPPING APPLICATION
Cleveland State University CIS493. Mobile Application Development Using Android TUTORIAL. BUILDING A SIMPLE MAPPING APPLICATION The goal of this tutorial is to create a simple mapping application that
Data Tool Platform SQL Development Tools
Data Tool Platform SQL Development Tools ekapner Contents Setting SQL Development Preferences...5 Execution Plan View Options Preferences...5 General Preferences...5 Label Decorations Preferences...6
JDBC (Java / SQL Programming) CS 377: Database Systems
JDBC (Java / SQL Programming) CS 377: Database Systems JDBC Acronym for Java Database Connection Provides capability to access a database server through a set of library functions Set of library functions
A Brief Introduction to MySQL
A Brief Introduction to MySQL by Derek Schuurman Introduction to Databases A database is a structured collection of logically related data. One common type of database is the relational database, a term
3.GETTING STARTED WITH ORACLE8i
Oracle For Beginners Page : 1 3.GETTING STARTED WITH ORACLE8i Creating a table Datatypes Displaying table definition using DESCRIBE Inserting rows into a table Selecting rows from a table Editing SQL buffer
SQL - QUICK GUIDE. Allows users to access data in relational database management systems.
http://www.tutorialspoint.com/sql/sql-quick-guide.htm SQL - QUICK GUIDE Copyright tutorialspoint.com What is SQL? SQL is Structured Query Language, which is a computer language for storing, manipulating
ELET4133: Embedded Systems. Topic 15 Sensors
ELET4133: Embedded Systems Topic 15 Sensors Agenda What is a sensor? Different types of sensors Detecting sensors Example application of the accelerometer 2 What is a sensor? Piece of hardware that collects
Managing Objects with Data Dictionary Views. Copyright 2006, Oracle. All rights reserved.
Managing Objects with Data Dictionary Views Objectives After completing this lesson, you should be able to do the following: Use the data dictionary views to research data on your objects Query various
SQL Server. 2012 for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach
TRAINING & REFERENCE murach's SQL Server 2012 for developers Bryan Syverson Joel Murach Mike Murach & Associates, Inc. 4340 N. Knoll Ave. Fresno, CA 93722 www.murach.com [email protected] Expanded
Financial Data Access with SQL, Excel & VBA
Computational Finance and Risk Management Financial Data Access with SQL, Excel & VBA Guy Yollin Instructor, Applied Mathematics University of Washington Guy Yollin (Copyright 2012) Data Access with SQL,
getsharedpreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.
Android Storage Stolen from: developer.android.com data-storage.html i Data Storage Options a) Shared Preferences b) Internal Storage c) External Storage d) SQLite Database e) Network Connection ii Shared
Projet Android (LI260) Cours 4
Projet Android (LI260) Cours 4 Nicolas Baskiotis Université Pierre et Marie Curie (UPMC) Laboratoire d Informatique de Paris 6 (LIP6) S2-2013/2014 Résumé sur le multi-thread Service : facile opérations
2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA www.sybex.com
Essential SQL 2 Essential SQL This bonus chapter is provided with Mastering Delphi 6. It is a basic introduction to SQL to accompany Chapter 14, Client/Server Programming. RDBMS packages are generally
Logi Ad Hoc Reporting System Administration Guide
Logi Ad Hoc Reporting System Administration Guide Version 11.2 Last Updated: March 2014 Page 2 Table of Contents INTRODUCTION... 4 Target Audience... 4 Application Architecture... 5 Document Overview...
Working with the Geodatabase Using SQL
An ESRI Technical Paper February 2004 This technical paper is aimed primarily at GIS managers and data administrators who are responsible for the installation, design, and day-to-day management of a geodatabase.
Object Oriented Databases. OOAD Fall 2012 Arjun Gopalakrishna Bhavya Udayashankar
Object Oriented Databases OOAD Fall 2012 Arjun Gopalakrishna Bhavya Udayashankar Executive Summary The presentation on Object Oriented Databases gives a basic introduction to the concepts governing OODBs
Webapps Vulnerability Report
Tuesday, May 1, 2012 Webapps Vulnerability Report Introduction This report provides detailed information of every vulnerability that was found and successfully exploited by CORE Impact Professional during
Relational Database: Additional Operations on Relations; SQL
Relational Database: Additional Operations on Relations; SQL Greg Plaxton Theory in Programming Practice, Fall 2005 Department of Computer Science University of Texas at Austin Overview The course packet
Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff
D80198GC10 Oracle Database 12c SQL and Fundamentals Summary Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff Level Professional Delivery Method Instructor-led
Oracle Database 12c: Introduction to SQL Ed 1.1
Oracle University Contact Us: 1.800.529.0165 Oracle Database 12c: Introduction to SQL Ed 1.1 Duration: 5 Days What you will learn This Oracle Database: Introduction to SQL training helps you write subqueries,
Database 10g Edition: All possible 10g features, either bundled or available at additional cost.
Concepts Oracle Corporation offers a wide variety of products. The Oracle Database 10g, the product this exam focuses on, is the centerpiece of the Oracle product set. The "g" in "10g" stands for the Grid
Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification
Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 Outline More Complex SQL Retrieval Queries
More SQL: Assertions, Views, and Programming Techniques
9 More SQL: Assertions, Views, and Programming Techniques In the previous chapter, we described several aspects of the SQL language, the standard for relational databases. We described the SQL statements
Programming Database lectures for mathema
Programming Database lectures for mathematics students April 25, 2015 Functions Functions are defined in Postgres with CREATE FUNCTION name(parameter type,...) RETURNS result-type AS $$ function-body $$
DbSchema Tutorial with Introduction in SQL Databases
DbSchema Tutorial with Introduction in SQL Databases Contents Connect to the Database and Create First Tables... 2 Create Foreign Keys... 7 Create Indexes... 9 Generate Random Data... 11 Relational Data
SAP Business Objects Business Intelligence platform Document Version: 4.1 Support Package 7 2015-11-24. Data Federation Administration Tool Guide
SAP Business Objects Business Intelligence platform Document Version: 4.1 Support Package 7 2015-11-24 Data Federation Administration Tool Guide Content 1 What's new in the.... 5 2 Introduction to administration
Embedded SQL programming
Embedded SQL programming http://www-136.ibm.com/developerworks/db2 Table of contents If you're viewing this document online, you can click any of the topics below to link directly to that section. 1. Before
Oracle Database: SQL and PL/SQL Fundamentals NEW
Oracle University Contact Us: 001-855-844-3881 & 001-800-514-06-97 Oracle Database: SQL and PL/SQL Fundamentals NEW Duration: 5 Days What you will learn This Oracle Database: SQL and PL/SQL Fundamentals
ETL Process in Data Warehouse. G.Lakshmi Priya & Razia Sultana.A Assistant Professor/IT
ETL Process in Data Warehouse G.Lakshmi Priya & Razia Sultana.A Assistant Professor/IT Outline ETL Extraction Transformation Loading ETL Overview Extraction Transformation Loading ETL To get data out of
Oracle Database: SQL and PL/SQL Fundamentals
Oracle University Contact Us: +966 12 739 894 Oracle Database: SQL and PL/SQL Fundamentals Duration: 5 Days What you will learn This Oracle Database: SQL and PL/SQL Fundamentals training is designed to
Chapter 9 Java and SQL. Wang Yang [email protected]
Chapter 9 Java and SQL Wang Yang [email protected] Outline Concern Data - File & IO vs. Database &SQL Database & SQL How Connect Java to SQL - Java Model for Database Java Database Connectivity (JDBC)
IT2305 Database Systems I (Compulsory)
Database Systems I (Compulsory) INTRODUCTION This is one of the 4 modules designed for Semester 2 of Bachelor of Information Technology Degree program. CREDITS: 04 LEARNING OUTCOMES On completion of this
Physical Design. Meeting the needs of the users is the gold standard against which we measure our success in creating a database.
Physical Design Physical Database Design (Defined): Process of producing a description of the implementation of the database on secondary storage; it describes the base relations, file organizations, and
Advanced SQL. Jim Mason. www.ebt-now.com Web solutions for iseries engineer, build, deploy, support, train 508-728-4353. jemason@ebt-now.
Advanced SQL Jim Mason [email protected] www.ebt-now.com Web solutions for iseries engineer, build, deploy, support, train 508-728-4353 What We ll Cover SQL and Database environments Managing Database
CHAPTER 2 DATABASE MANAGEMENT SYSTEM AND SECURITY
CHAPTER 2 DATABASE MANAGEMENT SYSTEM AND SECURITY 2.1 Introduction In this chapter, I am going to introduce Database Management Systems (DBMS) and the Structured Query Language (SQL), its syntax and usage.
Relational Databases. Christopher Simpkins [email protected]
Relational Databases Christopher Simpkins [email protected] Relational Databases A relational database is a collection of data stored in one or more tables A relational database management system
www.gr8ambitionz.com
Data Base Management Systems (DBMS) Study Material (Objective Type questions with Answers) Shared by Akhil Arora Powered by www. your A to Z competitive exam guide Database Objective type questions Q.1
Chapter 8. SQL-99: SchemaDefinition, Constraints, and Queries and Views
Chapter 8 SQL-99: SchemaDefinition, Constraints, and Queries and Views Data Definition, Constraints, and Schema Changes Used to CREATE, DROP, and ALTER the descriptions of the tables (relations) of a database
Oracle Database: SQL and PL/SQL Fundamentals
Oracle University Contact Us: 1.800.529.0165 Oracle Database: SQL and PL/SQL Fundamentals Duration: 5 Days What you will learn This course is designed to deliver the fundamentals of SQL and PL/SQL along
A basic create statement for a simple student table would look like the following.
Creating Tables A basic create statement for a simple student table would look like the following. create table Student (SID varchar(10), FirstName varchar(30), LastName varchar(30), EmailAddress varchar(30));
Oracle Database 10g Express
Oracle Database 10g Express This tutorial prepares the Oracle Database 10g Express Edition Developer to perform common development and administrative tasks of Oracle Database 10g Express Edition. Objectives
Oracle Database: SQL and PL/SQL Fundamentals NEW
Oracle University Contact Us: + 38516306373 Oracle Database: SQL and PL/SQL Fundamentals NEW Duration: 5 Days What you will learn This Oracle Database: SQL and PL/SQL Fundamentals training delivers the
Part A: Data Definition Language (DDL) Schema and Catalog CREAT TABLE. Referential Triggered Actions. CSC 742 Database Management Systems
CSC 74 Database Management Systems Topic #0: SQL Part A: Data Definition Language (DDL) Spring 00 CSC 74: DBMS by Dr. Peng Ning Spring 00 CSC 74: DBMS by Dr. Peng Ning Schema and Catalog Schema A collection
Introduction to SQL and database objects
Introduction to SQL and database objects IBM Information Management Cloud Computing Center of Competence IBM Canada Labs 1 2011 IBM Corporation Agenda Overview Database objects SQL introduction The SELECT
BCA. Database Management System
BCA IV Sem Database Management System Multiple choice questions 1. A Database Management System (DBMS) is A. Collection of interrelated data B. Collection of programs to access data C. Collection of data
Triggers & Packages. {INSERT [OR] UPDATE [OR] DELETE}: This specifies the DML operation.
Triggers & Packages An SQL trigger is a mechanism that automatically executes a specified PL/SQL block (referred to as the triggered action) when a triggering event occurs on the table. The triggering
Introduction to Triggers using SQL
Introduction to Triggers using SQL Kristian Torp Department of Computer Science Aalborg University www.cs.aau.dk/ torp [email protected] November 24, 2011 daisy.aau.dk Kristian Torp (Aalborg University) Introduction
LAB 6: Code Generation with Visual Paradigm for UML and JDBC Integration
LAB 6: Code Generation with Visual Paradigm for UML and JDBC Integration OBJECTIVES To understand the steps involved in Generating codes from UML Diagrams in Visual Paradigm for UML. Exposure to JDBC integration
History of SQL. Relational Database Languages. Tuple relational calculus ALPHA (Codd, 1970s) QUEL (based on ALPHA) Datalog (rule-based, like PROLOG)
Relational Database Languages Tuple relational calculus ALPHA (Codd, 1970s) QUEL (based on ALPHA) Datalog (rule-based, like PROLOG) Domain relational calculus QBE (used in Access) History of SQL Standards:
MAP524/DPS924 MOBILE APP DEVELOPMENT (ANDROID) MIDTERM TEST OCTOBER 2013 STUDENT NAME STUDENT NUMBER
MAP524/DPS924 MOBILE APP DEVELOPMENT (ANDROID) MIDTERM TEST OCTOBER 2013 STUDENT NAME STUDENT NUMBER Please answer all questions on the question sheet This is an open book/notes test. You are allowed to
D61830GC30. MySQL for Developers. Summary. Introduction. Prerequisites. At Course completion After completing this course, students will be able to:
D61830GC30 for Developers Summary Duration Vendor Audience 5 Days Oracle Database Administrators, Developers, Web Administrators Level Technology Professional Oracle 5.6 Delivery Method Instructor-led
Apache Cassandra Query Language (CQL)
REFERENCE GUIDE - P.1 ALTER KEYSPACE ALTER TABLE ALTER TYPE ALTER USER ALTER ( KEYSPACE SCHEMA ) keyspace_name WITH REPLICATION = map ( WITH DURABLE_WRITES = ( true false )) AND ( DURABLE_WRITES = ( true
IT2304: Database Systems 1 (DBS 1)
: Database Systems 1 (DBS 1) (Compulsory) 1. OUTLINE OF SYLLABUS Topic Minimum number of hours Introduction to DBMS 07 Relational Data Model 03 Data manipulation using Relational Algebra 06 Data manipulation
Getting Started: Creating a Simple App
Getting Started: Creating a Simple App What You will Learn: Setting up your development environment Creating a simple app Personalizing your app Running your app on an emulator The goal of this hour is
Services. Relational. Databases & JDBC. Today. Relational. Databases SQL JDBC. Next Time. Services. Relational. Databases & JDBC. Today.
& & 1 & 2 Lecture #7 2008 3 Terminology Structure & & Database server software referred to as Database Management Systems (DBMS) Database schemas describe database structure Data ordered in tables, rows
Database Programming. Week 10-2. *Some of the slides in this lecture are created by Prof. Ian Horrocks from University of Oxford
Database Programming Week 10-2 *Some of the slides in this lecture are created by Prof. Ian Horrocks from University of Oxford SQL in Real Programs We have seen only how SQL is used at the generic query
v1.1.0 SimpleSQL SQLite manager for Unity3D echo17.com
v1.1.0 SimpleSQL SQLite manager for Unity3D echo17.com Table of Contents Table of Contents................................................................ ii 1. Overview 2. Workflow...................................................................
Using SQL Server Management Studio
Using SQL Server Management Studio Microsoft SQL Server Management Studio 2005 is a graphical tool for database designer or programmer. With SQL Server Management Studio 2005 you can: Create databases
Database Administration with MySQL
Database Administration with MySQL Suitable For: Database administrators and system administrators who need to manage MySQL based services. Prerequisites: Practical knowledge of SQL Some knowledge of relational
not at all a manual simply a quick how-to-do guide
not at all a manual simply a quick how-to-do guide As a general rule, the GUI implemented by spatialite-gis is closely related to the one implemented by the companion app spatialite-gui So, if you are
A table is a collection of related data entries and it consists of columns and rows.
CST 250 MySQL Notes (Source: www.w3schools.com) MySQL is the most popular open-source database system. What is MySQL? MySQL is a database. The data in MySQL is stored in database objects called tables.
5.1 Database Schema. 5.1.1 Schema Generation in SQL
5.1 Database Schema The database schema is the complete model of the structure of the application domain (here: relational schema): relations names of attributes domains of attributes keys additional constraints
Microsoft Access 3: Understanding and Creating Queries
Microsoft Access 3: Understanding and Creating Queries In Access Level 2, we learned how to perform basic data retrievals by using Search & Replace functions and Sort & Filter functions. For more complex
Specialized Programme on Web Application Development using Open Source Tools
Specialized Programme on Web Application Development using Open Source Tools Objective: At the end of the course, Students will be able to: Understand various open source tools(programming tools and databases)
SQL NULL s, Constraints, Triggers
CS145 Lecture Notes #9 SQL NULL s, Constraints, Triggers Example schema: CREATE TABLE Student (SID INTEGER PRIMARY KEY, name CHAR(30), age INTEGER, GPA FLOAT); CREATE TABLE Take (SID INTEGER, CID CHAR(10),
1 SQL Data Types and Schemas
COMP 378 Database Systems Notes for Chapters 4 and 5 of Database System Concepts Advanced SQL 1 SQL Data Types and Schemas 1.1 Additional Data Types 1.1.1 User Defined Types Idea: in some situations, data
Android Development. Marc Mc Loughlin
Android Development Marc Mc Loughlin Android Development Android Developer Website:h:p://developer.android.com/ Dev Guide Reference Resources Video / Blog SeCng up the SDK h:p://developer.android.com/sdk/
Knocker main application User manual
Knocker main application User manual Author: Jaroslav Tykal Application: Knocker.exe Document Main application Page 1/18 U Content: 1 START APPLICATION... 3 1.1 CONNECTION TO DATABASE... 3 1.2 MODULE DEFINITION...
Building Database-Powered Mobile Applications
132 Informatica Economică vol. 16, no. 1/2012 Building Database-Powered Mobile Applications Paul POCATILU Bucharest University of Economic Studies [email protected] Almost all mobile applications use persistency
Creating a List UI with Android. Michele Schimd - 2013
Creating a List UI with Android Michele Schimd - 2013 ListActivity Direct subclass of Activity By default a ListView instance is already created and rendered as the layout of the activity mylistactivit.getlistview();
SQL Injection Attack Lab Using Collabtive
Laboratory for Computer Security Education 1 SQL Injection Attack Lab Using Collabtive (Web Application: Collabtive) Copyright c 2006-2011 Wenliang Du, Syracuse University. The development of this document
Android Studio Application Development
Android Studio Application Development Belén Cruz Zapata Chapter No. 4 "Using the Code Editor" In this package, you will find: A Biography of the author of the book A preview chapter from the book, Chapter
The Structured Query Language. De facto standard used to interact with relational DB management systems Two major branches
CSI 2132 Tutorial 6 The Structured Query Language (SQL) The Structured Query Language De facto standard used to interact with relational DB management systems Two major branches DDL (Data Definition Language)
Evaluation. Copy. Evaluation Copy. Chapter 7: Using JDBC with Spring. 1) A Simpler Approach... 7-2. 2) The JdbcTemplate. Class...
Chapter 7: Using JDBC with Spring 1) A Simpler Approach... 7-2 2) The JdbcTemplate Class... 7-3 3) Exception Translation... 7-7 4) Updating with the JdbcTemplate... 7-9 5) Queries Using the JdbcTemplate...
CS 2316 Data Manipulation for Engineers
CS 2316 Data Manipulation for Engineers SQL Christopher Simpkins [email protected] Chris Simpkins (Georgia Tech) CS 2316 Data Manipulation for Engineers SQL 1 / 26 1 1 The material in this lecture
Temporal Features in SQL standard
WG2 N1536 WG3: KOA-046 Temporal Features in SQL standard Krishna Kulkarni, IBM Corporation [email protected] May 13, 2011 1 Agenda Brief description of the SQL standard List of features in the latest
Oracle SQL. Course Summary. Duration. Objectives
Oracle SQL Course Summary Identify the major structural components of the Oracle Database 11g Create reports of aggregated data Write SELECT statements that include queries Retrieve row and column data
Object Relational Database Mapping. Alex Boughton Spring 2011
+ Object Relational Database Mapping Alex Boughton Spring 2011 + Presentation Overview Overview of database management systems What is ORDM Comparison of ORDM with other DBMSs Motivation for ORDM Quick
Instant SQL Programming
Instant SQL Programming Joe Celko Wrox Press Ltd. INSTANT Table of Contents Introduction 1 What Can SQL Do for Me? 2 Who Should Use This Book? 2 How To Use This Book 3 What You Should Know 3 Conventions
Guide to SQL Programming: SQL:1999 and Oracle Rdb V7.1
Guide to SQL Programming: SQL:1999 and Oracle Rdb V7.1 A feature of Oracle Rdb By Ian Smith Oracle Rdb Relational Technology Group Oracle Corporation 1 Oracle Rdb Journal SQL:1999 and Oracle Rdb V7.1 The
N3458: Simple Database Integration in C++11
N3458: Simple Database Integration in C++11 Thomas Neumann Technische Univeristät München [email protected] 2012-10-22 Many applications make use of relational database to store and query their data. However,
WI005 - Offline data sync con SQLite in Universal Windows Platform
WI005 - Offline data sync con SQLite in Universal Windows Platform presenta Erica Barone Microsoft Technical Evangelist @_ericabarone [email protected] Massimo Bonanni Microsoft MVP, Intel Black Belt
Lab 9 Access PreLab Copy the prelab folder, Lab09 PreLab9_Access_intro
Lab 9 Access PreLab Copy the prelab folder, Lab09 PreLab9_Access_intro, to your M: drive. To do the second part of the prelab, you will need to have available a database from that folder. Creating a new
Intro to Databases. ACM Webmonkeys 2011
Intro to Databases ACM Webmonkeys 2011 Motivation Computer programs that deal with the real world often need to store a large amount of data. E.g.: Weather in US cities by month for the past 10 years List
