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.

Slides:



Advertisements
Similar presentations
Connecting to Databases. connecting to DB DB server typically a standalone application Server runs on localhost for smaller sites –i.e. Same machine as.
Advertisements

Connecting to Databases. relational databases tables and relations accessed using SQL database -specific functionality –transaction processing commit.
19 augustus 2003augustus 2003 JSP-2. BICT 2JDBC BICT 3Install MySQL Download MySQL daemon – Free – Windows version… Start Daemon – Mysqld-nt.exe Download.
JDBC. Java Database Connectivity (JDBC) Use the java.sql package to query and update the database. JDBC is an API that allows java to communicate with.
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
Java Database Connectivity JDBC ICW Lecture 12 Errol Thompson.
JDBC. JDBC (Java Database Connectivity): JDBC is an API for the Java programming language that defines how a client may access a database. It provides.
Java Database Connectivity (JDBC) java.sql package to query and update the database. JDBC is an API that allows java to communicate with a database server.
Advanced Java Programming – Eran Toch Methodologies in Information System Development Tutorial: Advanced Java Programming and Database connection Eran.
MC365 JDBC in Servlets. Today We Will Cover: DBVisualizer Using JDBC in servlets Using properties files.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Murali Mani Web Interface. Murali Mani Options PHP with mySQL JSP/Servlets with JDBC on mySQL/Oracle Others …
Three-Tier Architecture Oracle DB Server Apache Tomcat App Server Microsoft Internet Explorer HTML Tuples HTTP Requests JDBC Requests Java Server Pages.
Java MS Access database connectivity Follow these steps: 1)Go to the start->Control Panel->Administrative Tools- > data sources. 2)Click Add button and.
CIS 270—App Dev II Big Java Chapter 22 Relational Databases.
Microsoft Windows 2003 Server. Client/Server Environment Many client computers connect to a server.
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
CSCI 6962: Server-side Design and Programming
1 Java Database Connection (JDBC) There are many industrial-strength DBMS's commercially available in the market. Oracle, DB2, and Sybase are just a few.
Overview of JDBC and Pro*C 1 Overview of JDBC,Pro*C and Oracle connectivity on Omega CSE 5330 – Database Systems.
CSCI 6962: Server-side Design and Programming JDBC Database Programming.
Beginning Databases with JDBC Mike Bradley Adapted from and notes by Kevin Parker, Ph.D.
CSE 305 Theory of Database Tutorial on Connecting with Sybase from Java program and Developing GUI Jalal Mahmud, TA, CSE 305.
 2004 Keith Vander Linden. All Rights Reserved. Calvin CollegeDepartment of Computer Science(1/25) Database Programming with JDBC Keith Vander Linden.
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.
JAVA Database Access. JDBC The Java Database Connectivity (JDBC) API is the industry standard for database- independent connectivity between the Java.
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.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Accessing Database using JDBC. JDBC Objectives Gain basic knowledge of Java JDBC Become familiar with the basics of interacting with a database using.
Copyright  Oracle Corporation, All rights reserved. 6 Accessing a Database Using the JDBC API.
Java Database Connectivity. Java and the database Database is used to store data. It is also known as persistent storage as the data is stored and can.
JDBC Database Programming in Java Prepared by., Mrs.S.Amudha AP/SWE.
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.
COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction.
JDBC IV IS Outline  Quiz 1  Stored procedures  Batch processing  Transactions  Homework #2.
EXAMPLE I An application showing JDBC access to Cloudscape.
CSI 3125, Preliminaries, page 1 JDBC. CSI 3125, Preliminaries, page 2 JDBC JDBC stands for Java Database Connectivity, which is a standard Java API (application.
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
Basics of JDBC.
JDBC (Java Database Connectivity)
SQL SERVER 2008 Installation Guide A Step by Step Guide Prepared by Hassan Tariq.
Database Programming With Java & JDBC Reading: DD Ch. 18, pp al/jdbc/index.html, or anything covering JDBC.
1 JDBC – Java Database Connectivity CS , Spring 2010.
Using Oracle JDBC How to Run JDBC on Your Account Communication Mechanism Using Metadata Building a Database Auto Commit v.s Atomic Transaction.
CS 440 Database Management Systems Stored procedures & OR mapping 1.
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.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
JDBC IV IS Outline  Batch processing  Transactions  Homework #2  Examples.
ASP.NET Programming with C# and SQL Server First Edition
CS3220 Web and Internet Programming Database Access with JDBC
1st Semester, 2017 Sanghyun Park
JDBC 15-Apr-18.
JDBC – Java Database Connectivity
Web Technologies IT230 Dr Mohamed Habib.
CS320 Web and Internet Programming Database Access with JDBC
JDBC 21-Aug-18.
HW#4 Making Simple BBS Using JDBC
Prof: Dr. Shu-Ching Chen TA: Sheng Guan
Basic Structure of SQL The basic structure of an SQL expression consists of three clauses: The select clause corresponds to the projection operation of.
JDBC 15-Nov-18.
Bolat Azamat, Kim Dongmin
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

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 the table 2

1.List the tools needed 2.Review Java 3.Learn JDBC (Java Database Connectivity) 4.Learn how to use the tools 5.Write and example 6.Run 3

To program in Java NetBeans IDE 6.5 Java JDK In fact you need any tool, however demos in this lecture will use NetBeans SQL Server 2008 The database that we already used in this class Microsoft SQL Server JDBC Driver 3.0 This is the driver that connect Java to SQL Can be download for free from the Internet 4

1.List the tools needed 2.Review Java 3.Learn JDBC (Java Database Connectivity) 4.Learn how to use the tools 5.Write and example 6.Run 5

This is the structure of a Java Program Class name should match the file name (Case sensitive) Should have one main function Program execution starts at the first executable line in the main function Arguments are received as Strings Number of arguments is in args.length 6

Scanner: used to input data input is a variable of type Scanner (able to read Integers, strings, ….) This program reads and integer and a string and then print the read values 7

Exception handling Exception  a problem (that might be or not accidental) Handling an exception allows a program to continue without compromising the execution. Example: if we divide by 0. The system will crash. However, there is a way to test the division (not the value) and react according to the results of the division itself. Overview Try to perform a task If there is a problem process the error 8

Overview try { ……. } catch ( ) { ….. } catch () { ….. } 9 We can have many catch. One after the other. When to use exception handling To process synchronous errors (statement execution) out of range array, overflow, …. Not to process asynchronous errors (read write from disk…) Java exception hierarchy Throwable Exception Error RuntimeExceptionIOExceptionAWTErrorThreadDeath OutOfMemoryError ClassCastExceptionNullPointerException ArithmeticException InputMismatchException ArrayIndexOutOfBoundsException

Example 10 Array declaration Initialization This cause an error! Catch the error Run it and see it!

Finally Optional Placed after the last catch block Will execute after try if no error or after last catch if error. Even if we exit try finally will execute. The only way to exit without running finally is to use System.exit. Normally used to release resources (as finalize). 11

1.List the tools needed 2.Review Java 3.Learn JDBC (Java Database Connectivity) 4.Learn how to use the tools 5.Write and example 6.Run 12

API (application-program interface) for a program to interact with a database server Application makes calls to Connect with the database server Send SQL commands to the database server Fetch tuples of result one-by-one into program variables JDBC (Java Database Connectivity) works with Java 13

JDBC is a Java API for communicating with database systems supporting SQL. JDBC supports a variety of features for querying and updating data, and for retrieving query results. JDBC also supports metadata retrieval, such as querying about relations present in the database and the names and types of relation attributes. Model for communicating with the database: Open a connection Create a “statement” object Execute queries using the Statement object to send queries and fetch results Exception mechanism to handle errors 14

public static void JDBCexample(String db, String user, String pass) { try { Class.forName ("Driver"); Connection conn = DriverManager.getConnection(db, user, pass); Statement stmt = conn.createStatement(); … Insert code here …. stmt.close(); conn.close(); } catch (SQLException sqle) { System.out.println("SQLException : " + sqle); } 15

Update to database try { stmt.executeUpdate( " Query "); } catch (Throwable sqle) { … } Execute query and fetch and print results ResultSet rs = stmt.executeQuery(" Query "); while ( rs.next() ) { System.out.println(" print result fields "); } Getting result fields: rs.getString(“String name”) or rs.getString(argument number) Dealing with Null values int a = rs.getInt(“a”); if (rs.wasNull()) ……. 16

Sometimes it is more convenient to use a PreparedStatement object for sending SQL statements to the database. This special type of statement is derived from the more general class, Statement If you want to execute a Statementobject many times, it usually reduces execution time to use a PreparedStatement object instead. The main feature of a PreparedStatement it is given a SQL statement when it is created. The advantage to this is that in most cases, this SQL statement is sent to the DBMS right away, where it is compiled. As a result, the PreparedStatement object contains not just a SQL statement, but a SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement SQL statement without having to compile it first. 17

Suppose we want to perform the following query insert into Instructor values (“1234”, “Samih”, “Dbase”, 5000); and that values will be taken from fields filled by the user This is how you should implement PreparedStatement pStmt = conn.prepareStatement( "insert into instructor values(?,?,?,?)"); pStmt.setString(1, “1111"); pStmt.setString(2, “Samih"); pStmt.setString(3, “Dbase"); pStmt.setInt(4, 5000); pStmt.executeUpdate(); pStmt.setString(1, “1234"); pStmt.executeUpdate(); 18 Values will be set later Argument number, value NOTE: Always use prepared statements, with user inputs as parameters

By default, each SQL statement is treated as a separate transaction that is committed automatically bad idea for transactions with multiple updates Can turn off automatic commit on a connection conn.setAutoCommit(false); Transactions must then be committed conn.commit(); or rolled back explicitly conn.rollback(); To turn on automatic commit conn.setAutoCommit(true) 19

1.List the tools needed 2.Review Java 3.Learn JDBC (Java Database Connectivity) 4.Learn how to use the tools 5.Write and example 6.Run 20

During setup of SQLServer 2008, you must select an authentication mode for the database engine. Two possible modes are available: Windows Authentication mode Mixed mode We need to prepare SQL Server to be authenticated using a username and a password Step 1: Open Microsoft SQL Server Management Studio and connect Step 2: Right click on the Server and select property Step 3: Select the Security tab and set Server Authentication as follow 21

Now that the mode is changed, you should be able to add a new user To do so: Right click on Security Select new Select Login In the login – New window Enter a Login name A password Confirm password 22

Now that the new user is created (Sarah) You need to give this new user some privileges In Microsoft SQL Server Management Studio Click on Security Click on Logins Right click on the new user Select property 23 Make sure sysadmin is selected

Right click SQL server and choose restart in the object explorer Disconnect then connect as the new user Create a new database (JavaDB) for testing Close Microsoft SQL Server Management Studio Few more thinks to do… 24

In your JAVA program, you need the following information: IP Address Port address To find these information Go to SQL Server Configuration manager Double click on TCP/IP Select the IP Addresses TAB NOTE: IP and Port are in general The same for all installation 25

Download from the Internet (Free) Drivers are not part of the Java JDK The download is a zip file containing the following structure What we need is the file enu \ sqljdbc4.jar This file contains the Microsoft driver It worth reading the help file help \ default.htm 26

Open NetBeans Go to file / New Project For category  select Java For projects  select Java Application Click on Next Give a project name Make sure that those two options are not selected 27

The project SQL is now created Right click on the project name, select New / Java class Give a class name The new class file is created in the following directory 28

We are now ready to write code I will guide you line by line I will use print screens instead of text Lazy students prefer to copy / paste without understanding … print screens avoid that You are supposed to have some knowledge in Java programming We will use exception handling 29

1.List the tools needed 2.Review Java 3.Learn JDBC (Java Database Connectivity) 4.Learn how to use the tools 5.Write and example 6.Run 30

31 Library needed Class name, remember in Java this should match the file name Connection String Socket Database Should be already created in SQL Server Try / catch (exception handling) The driver. From sqljdbc4.jar Structure used to connect Structure used to write SQL statements Structure used to receive results

32

33 SQL Query

34 Close the result structure Close the statement structure Close the connection structure Performed when the code in try complete Reached if errors in the try block

1.List the tools needed 2.Review Java 3.Learn JDBC (Java Database Connectivity) 4.Learn how to use the tools 5.Write and example 6.Run 35

Before building the application, you need to add the file sqljdbc4.jar to the library To do so: In the project explorer Right click on Libraries Select Add JAR/Folder… Browse to the location of sqljdbc4.jar Select open At this point you are ready to build and run your program 36

Click on Run / Build Project or hit F11 Click Run / Run Project or hit F6 37

We know now that it is not that Hard Well, let’s talk about: the student’s responsibility to improve his programming skills The instructor’s responsibility to help and encourage Next advanced lecture! homework!!!! 38