Download presentation
Presentation is loading. Please wait.
Published byMarjorie Bradley Modified over 8 years ago
1
1
2
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
3
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
4
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
5
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
6
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
7
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
8
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
9
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
10
Example 10 Array declaration Initialization This cause an error! Catch the error Run it and see it!
11
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
12
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
13
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
14
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
15
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
16
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
17
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
18
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
19
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
20
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
21
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
22
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
23
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
24
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
25
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
26
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
27
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
28
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
29
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
30
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
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
32
33
33 SQL Query
34
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
35
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
36
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
37
Click on Run / Build Project or hit F11 Click Run / Run Project or hit F6 37
38
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.