Download presentation
Presentation is loading. Please wait.
Published byPhilip Porter Modified over 9 years ago
1
SQL in higher level languages
2
2 Why do we want to use SQL in a higher level language? 1)Read in data from file, manipulate data before insert into relation Loop until the EOF read values from file – higher level code manipulate values with higher level code insert into relation values (SQL) End loop
3
3 Why cont’d 2)Compute results based on result from query e.g. generate a report Query database Compute results from query Print results 3)Provide a user interface (Web) for SQL if the current one is lacking Prompt user for query Send query to DBMS Receive results Display results to user
4
4 Must have: to do 1) must read in values into C/C++ variables then use those values to insert using SQL still need SQL statement to insert, select tuples to do 2) must be able to manipulate results from SQL query, but mismatch between C/C++/PHP and SQL sets versus one record at a time to do 3) need to accept queries from user - create SQL queries
5
5 To do this? Given the query: Select * From department, employee Where dno=dnumber and lname=?? What is needed? –Variables in which to place result, select condition (Host variables) –Processing of result table (cursors) –Data structure for communicating with DBS in case of errors (SQLCA) –What if we want to process any query typed in? (Dynamic SQL) –Also must connect to the DB, must connect to DBMS connect :user_name identified by :user_pwd using :host_string;
6
6 To do this 1.Embedded SQL Precede each statement with EXEC SQL 2. Platform specific classes, interfaces Oracle’s OLE 3. Platform independent classes, interfaces JDBC 4. Programming language that controls a software application PHP
7
Embedded SQL Embedded SQL – not used much these days – basis for all others Precede each statement with EXEC SQL Embedded Select statement EXEC SQL Select [distinct] expr {, expr} into host_var {, host_var} From table_name [alias] {, table_name [alias]} [Where search_cond] [Group by col {, col}] [Having search_cond]
8
Embedded SQL Only returns 1 value: EXEC SQL select lname, salary into :lname, :sal From employee Where ssn=123456789; If Returns multiple values: char emp_name[50][20]; int emp_number[50]; float salary[50]; EXEC SQL SELECT ENAME, EMPNO, SAL INTO :emp_name, :emp_number, :salary FROM EMP WHERE SAL > 1000;
9
Embedded SQL EXEC SQL declare c1 cursor for Select essn, hours From WORKS_ON Where pno = :proj_id; EXEC SQL open c1; EXEC SQL fetch c1 into :essn_id, :hrs; while (sqlca.sqlcode == 0) // checks for EOT { cout << essn_id << “ “ << hrs << endl; EXEC SQL fetch c1 into :essn_id, :hrs; };
10
. 2. Platform specific classes, interfaces Oracle’s OLE a middleware product manufactured by Oracle Corporation that allows native access (no ODBC) to Oracle databases from client applications via Microsoft OLE (Object Linking and Embedding) and COM (Component Object Model) Native Access to Oracle and only Oracle databases Runs slightly faster than ODBC access Some people feel it is VERY convenient
11
OLE Use OLE Classes Example: execute SQL statements directly with the ExecuteSQL method. db.ExecuteSQL("insert into project values (:projectName, :projectNumber, :projectLocation, :departmentNumber)")
12
OLE Using a cursor: ODynaset results(db, "Select * from employee"); cout << "salary" << endl; cout << "========" << endl; double salary; while (!results.IsEOF()) { if (results.GetFieldValue ("salary", &salary) == OFAILURE) { cout << db.GetServerErrorText() << endl; // example of character string // char first [10]; // results.GetFieldValue("fname", first, 10); } else { cout << salary << endl; results.MoveNext(); } }
13
JDBC 3. Platform independent classes, interfaces JDBC
14
4. PHP (and MYSQL)
15
PHP Written as a set of CGI binaries in C in 1994 by R. Lerdorf –Didn’t just want to post his resume –Created PHP to display resume and collect data about page traffic, e.g. dynamic web pages –Personal Home Page tools publicly released 1995 –In 1998 became PHP: Hypertext Preprocessor
16
PHP Creates DYNAMIC web pages –HTML traditionally static –Contents regenerated every time visit or reload site (e.g. can include current time) PHP is a scripting language –a programming language that controls a software application (program is independent of any other application) –Strong at communicating with program components written in other languages E.g. can embed PHP statements within HTML –Script like a dialogue for play interpreted by actors PHP parser with web server and web browser, model similar to MS ASP.NET, Sun JavaServer Pages JSP
17
PHP Takes input from a file or stream containing text and PHP instructions Outputs stream of data for display PHP originally interpreted, not converted to binary executable files PHP 4 – parser compiles input to produce bytecode (semi-compiled) – Zend engine (better performance than interpreted PHP 3) PHP 5 – robust support for OO programming, better support for MySQL, support for SQLite, performance enhancements –SQLite – ACID compliant embedded relational DB contained in small C programming library. Source code in public domain. SQLite library is linked in and part of application program, uses simple function calls, reducing latency. Entire DB stored as a single file on a host machine. –PHP 6PHP 6 –PHP 7PHP 7
18
PHP - specifics Delimiters: or just PHP parses code within delimiters Code outside delimiter sent to output, not parsed Block comments /* */ Inline comments // #
19
PHP vs. C++ Similarities: –Requires semicolons after each statement ; –Types are nearly the same (booleans, integers, strings, etc.) –Syntax nearly the same (For/While/If) –Assignment is right to left ($num = 56;) –Object-Oriented (Class support, inheritance, virtuals, polymorphism) –Functions!
20
PHP Versus C++ Differences: –Variables begin with $ sign ($name = “John Doe”;) –No explicit declaration of variable types –Introduction of “lazy” functions (foreach, explode, mail) –No Function Overloading –“Hidden” functions-within-a-function –Compiled/interpreted during every page load –Documented! –Echo for output –Concatenate is dot.
21
PHP Versus C++ Web Specific: –Cookies and “Sessions” –Dynamic HTML based on user-defined logic –Interact and process a form’s action –Process URL Parameters –Easy Database Integration
22
Sample code <?php // do not put a space between ? and php Echo “Hello CS457”; // can use either “ or ‘ ?> To run this, only need to specify a link to this program - http://bama.ua.edu/~login/hello.php Example
23
Easy Database Integration For example: MySQL
24
MySQL is a relational DBMS Has many of the same capabilities as traditional DBMSs (newest releases) MySQL queries mostly the same as SQL in Oracle (subsidiary of Sun) Popular for web databases It’s freeware!
25
MariaDB open source – community maintenance GNU GPL Fork of MySQL High compatibility with MySQL Developer (“Monty” Widenius) of MariaDB is founder of MySQL –sold it to Sun (bought by Oracle) for $1B Maria is his daughter
26
You can connect to MySQL directly OR You can connect to MySQL through.php
27
Connecting directly You can use a tool to create tables, insert them into your DB, query tables, etc. Possible tools: –Toad: http://www.quest.com/toad-for-mysql/http://www.quest.com/toad-for-mysql/ –phpmyadmin
28
MySQL Or you can use a command line You must be able to connect to the machine hosting the MySQL DB
29
MySQL To use a command line To start up MySQL type in: mysql –u yourlogin –D yourlogin_db –p [–h IP_address ] It will then prompt you for your password You need to specify a db to use, that is the –D parameter above
30
MySQL commands Can connect directly to MySQL: mysql> SHOW databases; mysql> USE db_name; // must specify this each time mysql> SHOW tables; mysql> DESCRIBE table_name; mysql> create table … mysql> insert into table values (… mysql> select * from table_name; mysql> delete … mysql> update
31
You can connect to MySQL directly OR You can connect to MySQL through.php, ruby on rails, etc.
32
Some php mysql functions Connecting to MySQL through PHP –Mysql_connect (“IP_address”, “login”, “pw”) –Mysql_select_db (‘name_db’, $link_id) –mysql_query (string [, resource $link_id]) Executes a query, place result in variable, like a cursor Resource specifies a connection, otherwise last connection opened used Returns a special variable holding a reference to external resource –mysql_error ( ) Returns error message from previous sql operation –mysql_fetch_array ($result, how) Returns array corresponding to fetched row, moves pointer to next row Traverses through cursor of query result How is either mysql_assoc (use col. names) or mysql_num (use index number) or mysql_both –Mysql_num_fields ( $result) Returns number of columns in table (fields in recordset) http://dk1.php.net/mysql_query
33
PHP and MySQL – ex1 <?php $link=mysql_connect (“vrbsky-oracle.cs.ua.edu”, “login”, “pw”); mysql_select_db('svrbsky_db') or die('Cannot select database'); $query = 'CREATE TABLE testit( '. 'id INT NOT NULL, '. 'age int)'; $result = mysql_query($query, $link); if(!$result) {die( 'Error in SQL: '. mysql_error());} echo "table created"; mysql_close($link); ?>
34
Example 1
35
Example ex2 <?php echo "Welcome to Vrbsky's DB"; // Connect to MySQL $link = mysql_connect(“vrbsky-oracle.cs.ua.edu", “login", “pw"); if (!$link) {die('Not connected: '. mysql_error()); } // see if connected // Select DB will use mysql_select_db('svrbsky') or die ('Could not select database'); // see if worked // Now the query $query = "Select * from testit"; // testit has 2 columns, id and age $result = mysql_query($query, $link); if (!$result) {die( 'Error in SQL: '. mysql_error());} // process results using cursor while ($row = mysql_fetch_array($result)) { echo " "; //horizontal line echo "id: ". $row["id"]. " "; echo "age: ". $row["age"]. " "; } mysql_free_result ($result); mysql_close($link); // disconnecting from MySQL ?>
36
Try example 2
37
Accessing result rows <?php $link=mysql_connect (“vrbsky-oracle.cs.ua.edu", “login", “pw"); mysql_select_db('svrbsky') or die('Cannot select database'); $query = "SELECT id, age FROM testit"; $result = mysql_query($query, $link); // Using an index while($row = mysql_fetch_array($result, MYSQL_NUM)) { echo “ID:{$row[0]} ". “Age: {$row[1]} "; } mysql_close($link); ?>
38
Example using index values
39
Forms and input Can use HTML to create forms Users can input values to use as host variables in calls to mysql
40
HTML code The following code uses a form to ask for input values to a table When user inputs values, event (action) occurs and php code is executed To use those values in php file, must use $_POST[‘var_name’]
41
$_POST function variables from a form will be placed into $_POST –$_ POST is an associative array (key, value) –Index into array is form data name –Info sent from form –POST is a superglobal variable, available in all scopes –With POST no limits on the amount of info to send Different from $_GET function where –Info sent is displayed in browser’s address bar –Max 100 characters
42
HTML and PHP and MYSQL ex3.html ID Age
43
PHP code PHP code places values input from form into its own local variables Connects to database Inserts values into tables Prints out values
44
example3.php <?php // This is example3.php used in previous.htm code $link = mysql_connect(“vrbsky-oracle.cs.ua.edu", “login", “pw"); if (!$link) {die('Not connected: '. mysql_error()); } mysql_select_db('svrbsky') or die ('Could not select database'); //have 2 host variables $id= $_POST['id']; $age = $_POST['age']; //the query $query = "insert into testit values ('$id', '$age')"; $result = mysql_query($query); if (!$result) {die('SQL error: '. mysql_error());} mysql_close($link); print " "; print " You have just entered this record "; print "ID: $id "; print "Age: $age"; print " "; ?>
45
Example 3 example 2
46
Dynamic query
47
Example HTML and PHP ex4.html Complete the Select Statement Select
48
<?php //This is example4.php referenced in previous.html code $link = mysql_connect('vrbsky-oracle.cs.ua.edu', “login", “pw"); if(!$link) { die('Not connected: '.mysql_error);} mysql_select_db('test'); // isset tests if the value of the variable is set if(isset($_POST['select'])) { //$select = 'select '.$_POST['select']; //echo $select; //can have problems with col=.string., so must get rid of \.s inserted by php for mysql| $select = stripslashes('select '.$_POST['select']); echo $select; $result = mysql_query($select, $link); if(!$result) { echo mysql_error(); } else { while($row = mysql_fetch_array($result, MYSQL_NUM)) { echo " "; // horizontal line echo " "; for($count = 0; $count < 10; $count++) { if(isset($row[$count])) echo " {$row[$count]} "; if(!isset($row[$count]) && isset($row[++$count])) { echo " "; $count--; } } echo " "; } ?>
49
example4.php code segment There can be problems with col = ‘string’ so use stripslashes() $select = stripslashes(‘select’.$_POST[‘select’]);
50
http://bama.ua.edu/~svrbsky/ex4.html
51
Our set up You will use php on bama.ua.edu and MySQL on the vrbsky-oracle machine The steps on the next slides tell you how to set up your bama account
52
Our setup You need to use SSH Secure Shell to connect to bama.ua.edu (I use ssh client from windows) Use vim (or whatever) to create new PHP and HTML files OR you can just edit files locally then use SSH file transfer to the bama.ua.edu machine
53
First Step – to set up bama The first step is to create your php and html files on bama but make sure you have done the following first: Go to: “Change bama Shell” Web helper“Change bama Shell” Web helper –Then Put your Username and Password and check the box, bash (Bourne Again shell)- it will enable you to do both SSH, Telnet, FTP –Then SSH/ Telnet to: bama.ua.edu and you can access the public_html –Copy or place your all your php and html files in public_html, e.g. Hello.php
54
Test PHP on bama Create your php and html files on bama: Create/save a.php file using an editor Make sure the file is on the bama.ua.edu machine in the public_html directory Sample program: <?php Echo “Hello World”; ?> To run it, from a web browser, type in: http:// bama.ua.edu/~yourbamalogin/filename For example, I use: http://bama.ua.edu/~svrbsky/Hello.php
55
bama.ua.edu html php MySQL Your DB vrbsky-oracle 1 2 3 4
56
Running Examples Next copy some of the programs from examples in these slides using php and mySQL and run them. Make sure you change the login, password and database to yours Make sure you create any needed tables for the examples.
57
Lots of great links on the web to get into Disadvantage: How to determine what is error? FYI: phpmyadmin is a great tool if you are interested
58
Need 2 files: –1 for html 1 for php You can test your SQL statements first using Toad (or whatever)
59
For the assignment - insert tuples into your tables You can use a tool to insert tuples into your tables Possible tools: –Toad: http://www.quest.com/toad-for-mysql/http://www.quest.com/toad-for-mysql/ –Phpmyadmin Or Write can PHP code to: –insert tuples into your tables/views
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.