Presentation is loading. Please wait.

Presentation is loading. Please wait.

CompSci 280 S Introduction to Software Development

Similar presentations


Presentation on theme: "CompSci 280 S Introduction to Software Development"— Presentation transcript:

1 CompSci 280 S2 2107 Introduction to Software Development
MySQL Database Access

2 Today’s Agenda Topics: Reading: JDBC - MySQL Database Access
Introduction Make a connection Execute a SQL select statement Python MySQL Database Access Reading: Download Connector/Python Download Connector/J Lecture15

3 1.JDBC Architecture Java code calls JDBC library. JDBC loads a driver
Driver talks to a particular database Install the latest version of Connector/J. Copying the driver to your computer, then adding the location of it to your class path. Process any SQL statement with JDBC, follow these steps: Establishing a connection Create a statement Execute the query Process the ResultSet object Close the connection. Application JDBC Driver Database Lecture15

4 1.JDBC JDBC Object Classes
DriverManager Loads, chooses drivers Driver connects to actual database Connection a series of SQL statements to and from the DB Statement a single SQL statement ResultSet the records returned from a Statement DriverManager Driver Connection Statement ResultSet Lecture15

5 1.JDBC Setting up Driver for MySQL
Steps: Download Connector/J Save the file either in the current directory or extension directory Save the file in your current directory : C:\compsci280\ folder 1. Open Command prompt, type the following: OR 2. Create a CLASSPATH variable in the Environment Variables Save the file in extension folder C:\Program Files\java\jre1.xxx > lib > ext mysql-connector-java bin.jar Either set the classpath or save the jar file in the ext folder Set classpath= C:\compsci280\mysql-connector-java bin.jar;%CLASSPATH% .;C:\compsci280\mysql-connector-java bin.jar\; Lecture15

6 1.JDBC Establishing & Making a Connection
Before we can access data in a database, we must open a connection to the MySQL server. Steps: Loading the driver for MySQL Server database: Class.forName(“xxxDriver”); // depends on the particular Driver Making Connection Connects to given JDBC URL with given user name and password URL = “jdbc:mysql://host:3306/database_name”; Returns a connection object Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection(URL, login, password); Parameter Description host studdb-mysql.fos.auckland.ac.nz username Your UPI password Password given from Database name stu_YOURUPI_COMPSCI_280_C_S2_2017 Lecture15

7 1.JDBC Example: TestConnection
Connection conn = null; try { Class.forName(JDBC_DRIVER); System.out.println("... Driver loaded."); conn = DriverManager.getConnection(URL, USER, PASS); if (conn != null) System.out.println("...MySQL Server connected."); else System.out.println("Failed to make connection!"); } catch (Exception e) { System.out.println(e); } finally { conn.close(); } catch (Exception e) {}; } If the output is: java.sql.SQLException: No suitable driver found for … Check the classpath if it has been set correctly. Lecture15

8 1.JDBC Executing a Statement
A Statement object is used for executing a SQL statement and obtaining the results produced by it. Steps: Create a Statement Object Execute the query To execute a query, call an execute method from Statement: ExecuteQuery: for select statements Execute a SQL statement that returns a single ResultSet. ExecuteUpdate: for insert/delete/update statements (extra) Execute a SQL INSERT, UPDATE or DELETE statement. Returns the number of rows changed stmt = con.createStatement(); sql = "SELECT * FROM EMPLOYEES"; rs = stmt.executeQuery(sql); Lecture15

9 1.JDBC Result Set A ResultSet provides access to a table of data generated by executing a Statement. Only one ResultSet per Statement can be open at once. The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. ResultSet Methods: boolean next() activates the next row the first call to next() activates the first row returns false if there are no more rows void close() disposes of the ResultSet allows you to re-use the Statement that created it Lecture15

10 1.JDBC ResultSet Methods
Type getType(int columnIndex) returns the given field as the given type fields indexed starting at 1 (not 0) Type.INTEGER = 4 Type. FLOAT = 6 Type. CHAR= 1 int findColumn(String columnName) looks up column index given column name int getInt(int columnIndex) double getDouble(int columnIndex) String getString(int columnIndex) Date getDate(int columnIndex) stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String coffeeName = rs.getString("FIRST_NAME "); ... } Lecture15

11 1.JDBC Example 2: Count the number of employees in the EMPLOYEES table: sql = "SELECT COUNT(*) FROM EMPLOYEES" if (conn != null) System.out.println("...MySQL Server connected."); stmt = conn.createStatement(); rs = stmt.executeQuery(sql); if (rs != null) { while (rs.next()) System.out.println(rs.getInt(1)); } 10 Lecture15

12 1.JDBC Example 3: Print last name and surname from the EMPLOYEES table: sql = "SELECT FIRST_NAME, LAST_NAME FROM EMPLOYEES" sql = "SELECT FIRST_NAME, LAST_NAME FROM EMPLOYEES" ... stmt = conn.createStatement(); rs = stmt.executeQuery(sql); if (rs != null) { while (rs.next()) System.out.printf("%s, %s%n", rs.getString(1), rs.getString(2)); } SUSAN, BROWN JIM, KERN MARTHA, WOODS ELLEN, OWENS HENRY, PERKINS CAROL, ROSE DAN, SMITH FRED, CAMPBELL PAULA, JACOBS NANCY, HOFFMAN Lecture15

13 2.Python MySQL Connector/Python
Commonly, Python applications will need to access a database of some sort. The Python standard for database interfaces is the Python DB-API. Most Python database interfaces adhere to this standard. You must download a separate DB API module for each database MySQL alone has the following interface modules to choose: MySQL for Python (import MySQLdb) MySQL Connector/Python (import mysql.connector) etc So which module do you choose? Well, as far as code-writing goes, it probably won’t make that much of a difference… Download and install MySQL Connector/Python mysql-connector-python py3.4-windows-x86-64bit.msi Remember to check your Python version Lecture15

14 2.Python Establishing & Making a Connection
Before we can access data in a database, we must open a connection to the MySQL server. The connect() creates a connection to the MySQL server and returns a Connection object. close() – close connection. commit() – commit pending transaction (if supported). rollback() – if supported by db, roll back to start of pending transaction. cursor() – return a Cursor object for the connection. import mysql.connector ... conn = mysql.connector.connect(user=my_user, password=my_password, host=my_host, database=my_database) Parameter Description host studdb-mysql.fos.auckland.ac.nz username Your UPI password Password given from Database name stu_YOURUPI_COMPSCI_280_C_S2_2017 Use these information to connect to your own database Lecture15

15 2.Python Creating Cursor object
Create a cursor object that allows Python code to execute database command. They are bound to the connection for the entire lifetime and all the commands are executed in the context of the database session wrapped by the connection. The following attributes should be available: description – a description of the cursor with up to seven fields. rowcount – number of rows produced by last execute method (-1 by default). Methods: close(): close the cursor object cursor = conn.cursor() Lecture15

16 2.Python Example 1 Steps: Connect the MySQL Database server
Create a cursor object import mysql.connector my_user = "" my_password = "" my_host = "studdb-mysql.fos.auckland.ac.nz" my_database = "stu_kng001_COMPSCI_280_C_S2_2016" try: conn = mysql.connector.connect(user=my_user, password=my_password, host=my_host, database=my_database) cursor = conn.cursor() print("Connected") except: print("Error: unable to fetch data") cursor.close() conn.close() Lecture15

17 2.Python Executing a SQL Query
Execute sql queries using the execute() method associated with the cursor object. Syntax: prepare and execute an operation with parameters where the second argument may be a list of parameter sequences. Examples: Count the number of employees in the EMPLOYEES table: c.execute[many](op, [params]) sql = "SELECT COUNT(*) FROM EMPLOYEES“ conn = mysql.connector.connect(user=my_user, password=my_password, host=my_host, database=my_database) cursor = conn.cursor() cursor.execute(sql) result = cursor.fetchone() print(result) Lecture15

18 2.Python Fetch data from database
Multiple ways to retrieve data: fetchall() Fetch all (remaining) rows of a query result, returning them as a sequence of sequences (e.g. a list of tuples) fetchmany(size) Fetch the next set of rows of a query result, returning a sequence of sequences. It will return number of rows that matches to the size argument. fetchone() Fetch the next row of a query result set, returning a single sequence or None when no more data is available. Lecture15

19 2.Python Example 3: One record: Multiple records:
Print the last name and surname from the EMPLOYEES table: 10 sql = "SELECT COUNT(*) FROM EMPLOYEES“ cursor.execute(sql) result = cursor.fetchone() print(result) SUSAN, BROWN JIM, KERN MARTHA, WOODS ELLEN, OWENS HENRY, PERKINS CAROL, ROSE DAN, SMITH FRED, CAMPBELL PAULA, JACOBS NANCY, HOFFMAN cursor.execute(sql) rows = cursor.fetchall() for row in rows: fname = row[0] lname = row[1] print( "%s, %s" % (fname, lname)) a list of tuples Lecture15

20 2.JDBC Introduction What is JDBC?
A Java API Interface for database communication (created in 1995) – provide mechanism to allow Java Applets/Application access to database JDBC = Java Database Connectivity JDBC helps you to write Java applications that manage these three programming activities: Connect to a data source, like a database Send queries and update statements to the database Retrieve and process the results received from the database in answer to your query JDBC is implemented via classes in the java.sql package Lecture15


Download ppt "CompSci 280 S Introduction to Software Development"

Similar presentations


Ads by Google