CompSci 280 S Introduction to Software Development

Slides:



Advertisements
Similar presentations
Basic JDBC Celsina Bignoli What is JDBC Industry standard for database- connectivity between the Java language and a wide range of.
Advertisements

15-Jun-15 JDBC. JDBC is a Sun trademark It is often taken to stand for Java Database Connectivity Java is very standardized, but there are many versions.
1 JDBC Java Database Connectivity. 2 c.pdf
1 JDBC: Java Database Connectivity. 2 Introduction to JDBC JDBC is used for accessing databases from Java applications Information is transferred from.
JDBC Overview Autumn 2001 Lecturer: C. DeJong. Relational Databases widespread use used via SQL (Structured Query Language) freely available powerful.
1 Lecture 29 More on JDBC Overview  Objectives of this lecture  JDBC and its Drivers  Connecting to Databases (Java’s Connection class)  Querying a.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
1 CSC 440 Database Management Systems JDBC This presentation uses slides and lecture notes available from
Overview of JDBC and Pro*C 1 Overview of JDBC,Pro*C and Oracle connectivity on Omega CSE 5330 – Database Systems.
CS178 Database Management “JDBC”. What is JDBC ? JDBC stands for “Java DataBase Connectivity” The standard interface for communication between a Java.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java/jsp program to connect to any database.
Beginning Databases with JDBC Mike Bradley Adapted from and notes by Kevin Parker, Ph.D.
Python MySQL Database Access
MySQL, Java, and JDBC CSE 3330 Southern Methodist University.
JDBC Tutorial MIE456 - Information Systems Infrastructure II Vinod Muthusamy November 4, 2004.
JDBC (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
Overview of JDBC and Pro*C 1 CSE 5330 – Database Systems.
CONTROLPANEL Java.sql package This package provides the APIs for accessing and processing data which is stored in the database especially relational.
Servlets Database Access. Agenda:  Setup Java Environment  Install Database  Install Database Drivers  Create Table and add records  Accessing a.
JDBC Java and Databases, including Postgress. JDBC l Developed by Industry leaders l Three main goals: –JDBC should be an SQL-level API –JDBC should capitalize.
JDBC. JDBC stands for Java Data Base Connectivity. JDBC is different from ODBC in that – JDBC is written in Java (hence is platform independent, object.
JDBC Java and Databases. RHS – SOC 2 JDBC JDBC – Java DataBase Connectivity An API (i.e. a set of classes and methods), for working with databases in.
1 JDBC Aum Amriteshwaryai Namah. 2 2 JDBC – Java DataBase Connectivity.
Accessing Database using JDBC. JDBC Objectives Gain basic knowledge of Java JDBC Become familiar with the basics of interacting with a database using.
WEB/DB1 DATABASE PROGRAMMING 3JDBC by the ASU Scholars.
JDBC – Java Database Concentricity
Chapter 25 Databases. Chapter Scope Database concepts Tables and queries SQL statements Managing data in a database Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25.
JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.
JDBC CS 124. JDBC Java Database Connectivity Database Access Interface provides access to a relational database (by allowing SQL statements to be sent.
Li Tak Sing COMPS311F. Database programming JDBC (Java Database Connectivity) Java version of ODBC (Open Database Connectivity) ODBC provides a standard.
COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction.
EXAMPLE I An application showing JDBC access to Cloudscape.
Database Access Using JDBC BCIS 3680 Enterprise Programming.
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
Basics of JDBC.
Umair Javed©2005 Enterprise Application Development Java Database Connectivity (JDBC) JDBC1.
Introduction to JDBC Instructor: Mohamed Eltabakh 1.
JDBC Java and Databases. SWC – JDBC JDBC – Java DataBase Connectivity An API (i.e. a set of classes and methods), for working with databases in.
1 JDBC – Java Database Connectivity CS , Spring 2010.
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
6-1 JAVA DATABASE CONNECTOR Colorado Technical University IT420 Tim Peterson.
CS422 Principles of Database Systems JDBC and Embedded SQL Chengyu Sun California State University, Los Angeles.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java program to connect to any database.
1. Writing a Java program to connect to SQL Server 2008 and Create a table Populate the table (insert data) Perform queries to retrieve information from.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
Instructor: Jinze Liu Fall /8/2016Jinze University of Kentucky 2 Database Project Database Architecture Database programming.
Database Programming Basic JDBC Programming Concepts.
MYSQL APPLICATIONS USING JAVA & JDBC CIS 430 –Database Concepts Victor Matos.
JSP and DB.
CS3220 Web and Internet Programming Database Access with JDBC
Lec - 14.
JDBC 15-Apr-18.
CompSci 280 S Introduction to Software Development
JDBC – Java Database Connectivity
CS320 Web and Internet Programming Database Access with JDBC
Advanced Web Automation Using Selenium
JDBC 21-Aug-18.
HW#4 Making Simple BBS Using JDBC
UNIT-2 Java Database Programming
JDBC.
JDBC 15-Nov-18.
Interacting with Database
JDBC – Java Database Connectivity
MSIS 655 Advanced Business Applications Programming
Using a Database with JDBC
JAVA DATABaSE CONNECTIVITY
JDBC Example.
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

CompSci 280 S2 2107 Introduction to Software Development MySQL Database Access

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 https://dev.mysql.com/downloads/connector/python/ Download Connector/J https://dev.mysql.com/downloads/connector/j/ Lecture15

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

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

1.JDBC Setting up Driver for MySQL Steps: Download Connector/J 5.1.43 https://dev.mysql.com/downloads/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-5.1.39-bin.jar Either set the classpath or save the jar file in the ext folder Set classpath= C:\compsci280\mysql-connector-java-5.1.39-bin.jar;%CLASSPATH% .;C:\compsci280\mysql-connector-java-5.1.39-bin.jar\; Lecture15

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 email Database name stu_YOURUPI_COMPSCI_280_C_S2_2017 Lecture15

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

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

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

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

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

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

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 https://dev.mysql.com/downloads/connector/python/ mysql-connector-python-2.1.7-py3.4-windows-x86-64bit.msi Remember to check your Python version Lecture15

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 email Database name stu_YOURUPI_COMPSCI_280_C_S2_2017 Use these information to connect to your own database Lecture15

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

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

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

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

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

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