Database Programming
Total Page:16
File Type:pdf, Size:1020Kb
University of Helsinki/ CS 17.2.2003 Introduction to Databases, Spring 2003 Database programming Programming Database Applications Embedded SQL Databases are rarely used thru direct query SQL-statements are written among programming interfaces language statements. SQL-statements carry special (Exec SQL) marks that identify then as being SQL Typically they are used thru application The marks are used by a pre-compiler that programs substitutes the SQL statements with calls of library Techniques to use databases in application functions programs include: The result of the pre-compiler is then compiled with a – Embedded SQL standard programming language compiler – Database Application Programming interface 2-phase compilation Library (database API) Pre-compilers are available from dbms suppliers for – Other interface that hide the database some programming languages (Ada, C, C++, Cobol, Pascal,…, Java) – A special database programming language Embedded SQL Example of Embedded SQL in Pascal function avgSalary(dept:integer):real; var Marked SQL- statement among PrePre-- Function library n: integer; programming language compilercompiler (database functions) statements (C+SQL) salSum: integer; #include SQLCA.INC EXEC SQL BEGIN DECLARE SECTION Standard programming var salary: integer; Language + ‘normal’ dpt: integer; Compiled ‘normal’ SQL statements as Compiled compilercompiler Parameters of function EXEC SQL END DECLARE SECTION programprogram calls Example of Embedded SQL in Pascal Concepts in embedded SQL begin Cursor EXEC SQL DECLARE salaryCursor CURSOR FOR SELECT salary from employee – Structure for processing the result of a query where department= :dpt; • Must be attached to a query (declare) n:=0; salSum:=0; dpt:= dept; • Is opened (open) = the attached query is executed using EXEC SQL open salaryCursor; the variable values of the execution time EXEC SQL fetch salaryCursor into :salary; • Is moved (fetch) = proceed to next record and transfer while sqlcode = 0 do begin data from the current record to program variables salSum := salSum + salary; • Is closed (close) = releases resources n := n + 1; EXEC SQL fetch salaryCursor into :salary; end; EXEC SQL close salaryCursor; if n > 0 then avgSalary := salSum/n else avgSalary := 0; end;. © Harri Laine 1 University of Helsinki/ CS 17.2.2003 Introduction to Databases, Spring 2003 Database programming Concepts in embedded SQL Programming using a database API A database operation may fail. The success Application programming interface (API) is of the operation must be tested after each library that provides the services of the operation. DBMS. Success may be tested by checking the value Supplier specific libraries: Native API of the variable sqlstate (or sqlcode according – For example OracleCLI = Oracle Call Level to the older standard). Both return 0 if the Interface operation succeeded and an error code it Supplier independent libraries failed. – For example ODBC (Microsoft Open Database Success may be also tested by defining error Connection), JDBC Java database connection handlers (WHENEVER something do – Make it possible to change dbms and even to use Handler) many dbms in the same program Programming using a database API JDBC Supplier independent libraries require a dbms Java database connection (JDBC) provides only a specific driver to work with a particular dbms few classes: DriverManager ODBC is the most common API – This class provides services for attaching the dbms specific – All suppliers provide ODBC drivers. driver and for establishing connections to the database, – Parameters passed in C-language style – DBms drivers are able to register themselves. Thus it is enough to load the driver, for example, using classByName JDBC provides the same ideas as ODBC but service. in Java – Here is the code for explicit registration of the driver – Some details of ODBC are hidden within class – DriverManager.registerdriver( definitions. new oracle.jdbc.OracleDriver()); JDBC JDBC Connection Connection con = – This class establishes a database connection DriverManager.getConnection( (session): • a connection between the application and the database – log in with some user account and password “jdbc:oracle:thin:@bodbacka.cs.helsinki.fi:1521:test”, – All database services need a connection – “scott”,”tiger”); Connection class connects service requests to the connection Establishes a connection using Oracle thin driver via – Connection should be closed when it is no longer port 1521 to computer bodbacka.cs.helsinki.fi and its needed test- database using user account scott and – DriverManager provides the method for creating a password tiger connection © Harri Laine 2 University of Helsinki/ CS 17.2.2003 Introduction to Databases, Spring 2003 Database programming JDBC JDBC Statement ResultSet – Environment for executing database operations – The answers obtained by executing a query – Provides, for example, methods – Corresponds to the cursor of embedded SQL – executeQuery - to execute queries – Method Statement.executeQuery() creates a – executeUpdate - to execute other operations ResultSet object • executeQuery accepts the actual query as its parameter Connection provides a methos for creationg statements Statement stmt= con.createStatement(); ResultSet rs= stmt.executeQuery( “select name from employee”); JDBC JDBC Answer processing using the methods of – Data may be only in program variables. ResultSet ResultSet: provides data type specific methods getType to transfer data from active row to program getString – Method next() activates the next row of the for Strings, getBoolean for booleans, getInt, answer. It returns true if such a row exists and getDate,…. otherwise false. First call activates the first row of the answer. – These functions use the column name or the column sequence number as their parameter –esim: – String a= rs.getString(“address”); // column address – Int p= rs.getInt(3); // third column JDBC JDBC Get-functions are able to perform some data type Statement stmt= con.createStatement(); conversions, for example to change integers to ResultSet rs= stmt.executeQuery( strings or vice versa. If conversion fails an “select name, address, salary from employee ” + SQLException is thrown. All error conditions cause “ order by name”); SQLException to be thrown. while (rs.next()) { Null values need special treatment. getString returns System.out.println(rs.getString(1) +”, “+ java.NULL in case of SQL null value, but, for rs.getString(2)+”, “+rs.getString(3)); example, getInt returns 0 (zero). To test whether the } value was null there is method wasNull. It is Output : parametrized like the get-methods. Lahtinen Kalle, Katu 6, 12000 Mäki Manu, Kuja5, 20000 © Harri Laine 3 University of Helsinki/ CS 17.2.2003 Introduction to Databases, Spring 2003 Database programming JDBC JDBC Statement that do not produce a result (insert, Parametrized operation: delete, update, create, alter, …) are executed – Database operations may always be executed by using Statement.executeUpdate-method. giving them as parameters for the methods executeUpdate and executeQuery. Sometimes example almost the same operations is used repeatedly Int empUpdated= with only minor changes. In these cases it might stmt.executeUpdate(“update employee “+ be useful to compile the query only once and “set salary= salary + 10000 ” + reuse the compiled query. “ where name= ‘Laine Harri’ ”); – Class PreparedStatement supports this way of programming. JDBC JDBC PreparedStatement pst = registerDriver con.prepareStatement( DriverManager external driver “select name,address,salary “+ “from employee “+ “where name like ?” ); getConnection Question mark indicates a parameter, It can be used to substitute a constant value. Connection PreparedStatement provides data type specific set-methods for assigning values for these parameters (setString for strings) prepareStatement Set methods have two parameters: createStatement – The sequence number of the question mark in the SQL-operation setXXXX and Statement PreparedStatement – The value to substitute the parameter –Example; pst.setString(1,”Smi%”); executeQuery Prepared statement has executeQuery and execute update methods, but these don’t need any parameter. next ResultSet getYYYY © Harri Laine 4.