COP4540 TUTORIAL PROFESSOR: DR SHU-CHING CHEN TA: H S IN-YU HA
OUTLINE Postgresql installation Introduction of JDBC Stored Procedure
POSTGRES INSTALLATION (1) Extract the source file Start the configuration (about one minute) Set up the prefix as the folder with your own permission Default would be home directory.
POSTGRES INSTALLATION (2) Compile all of your source code If the code was built correctly the last line would be Ready to install (less than one minute) Successfully install
POSTGRES INSTALLATION (3) Initialize database cluster Start the postgres server
OUTLINE Postgresql installation Introduction of JDBC Stored Procedure
JDBC Write once, Match all DBMS!! The Java Database connectivity Making a connection to a database Creating SQL or MySQL statements Executing queries in the database Viewing or Modifying the result records Oracle JDBC Driver Oracle Database Application JDBC Driver Interface SQL JDBC Driver MySQL JDBC Driver PostgreSQL JDBC Driver SQL Database MySQL Database PostgreSQL Database
STEPS OF CONNECTING DATABASE 1) Get the specific type of JDBC driver 2) Initializing the Driver 3) Start the Connection 4) Initialize one Statement object 5) Send out the SQL execute*() 6) Get the Resultset object which is returned by DBMS 7) Close the connection close()
(1) GET JDBC DRIVER Download driver from any DBMS company website Format: <DBMS_Name-JDBC-Type_n.jar> For example: postgresql-9.0-801.jdbc4.jar j Put it to any accessible library folder PostgreSQL JDBC Driver : http://jdbc.postgresql.org
(2) INITIALIZING THE DRIVER Importing JDBC Import java.sql.* Loading the server Class.forName("org.postgresql.Driver"); try { Class.forName("org.postgresql.Driver"); t l D i ") }catch(classnotfoundexception e) { System.out.println( Can t find Driver class "); }
(3) START THE CONNECTION String DRIVER = "org.postgresql.driver Driver"; String URL ="jdbc:postgresql://[ip]:5432/[db_name]"; String USER = "whoami"; String PASSWORD = "123456"; Connection conn = DriverManager.getConnection( getconnection( URL, USER, PASSWORD ); // DriverManager.getConnection( url ); System.out.println(conn.isReadOnly( ));... if ( conn!= null &&!conn.isclosed( ) ) { System.out.println( Successfully connect to database!"); } conn.close( );
(4) INITIALIZE ONE STATEMENT OBJECT AND (5)EXECUTE Statements stmt = conn.createstatement( ); ResultSet result = stmt.executequery( SELECT * FROM mytable ); Execute executequery() -> SQL for Searching and viewing executeupdate() -> SQL for Changing database s contents ExecuteQuery() Return results as row(s) () Use next() to move to next record, return a boolean value to indicate whether we have next record Use get<type>() to retrieve the data by attribute name or order
EXECUTE EXAMPLE Create / Update table Statements stmt = conn.createstatement( ); stmt.executeupdate( "CREATE TABLE jdemo ( title character varying(50),body text, id serial)"); stmt.executeupdate( ALTER TABLE jdemo ADD PRIMARY KEY (id) ); View data ResultSet result = stmt.executequery( executequery( SELECT * FROM jdemo ); while (result.next( )) { System.out.print(result.getInt( id ) + \t ); System.out.print(result.getString("title") + "\t"); System.out.println(result.getString("body")); i ( }
JDBC EXAMPLE 1. Import java.sql.*; 2. public class BasicResultSetExample { 2. public class BasicResultSetExample { 3. public static void main(string[] args) { 4. try{ 5. /** Loading the driver*/ 6. Class.forName(org.postgresql.Driver); 7. /** Getting Connection*/ 8. Connectioncon = DriverManager.getConnection(jdbc:postgresql://localhost:5432/test,root,root); 9. /** Creating Statement*/ 10. Statementstmt =con.createstatement(); 11 ResultSetrs=stmt executequery(select * from mytable); 11. ResultSetrs=stmt.executeQuery(select from mytable); 12. while(rs.next()) 13. { 14. System.out.print(Id is +rs.getint(id)); 15. System.out.println( Name is +rs.getstring(name)); 16 } 16. } 17. /** Closing the Connection*/ 18. stmt.close(); 19. con.close(); 20. }catch (Exceptione) { } ( p ){ 21. e.printstacktrace();} 22. } 23. }
OUTLINE Postgresql installation Introduction of JDBC Stored Procedure
WHAT ARE STORED PROCEDURES A stored procedure is an already written SQL statement that is saved in the database. Advantage Reduce roundtrips across the network Can make security easier to manage Are precompiled
STORED PROCEDURES - SQL How to run a stored procedures exec usp_displayallusers The SQL language inside the stored procedure SELECT * FROM USERLIST How to start with writing stored procedure A database management system A database built inside the database management system stem A text editor
FIRST STORED PROCEDURE /* Name: usp_displayallusers Description: displays all records and columns in USERLIST table Author: Tom O Neill Modification Log: Change Description Date Changed By Created procedure 7/15/2003 Tom O Neill */ CREATE PROCEDURE usp_displayallusers AS SELECT * FROM USERLIST
INPUT VARIABLES Input variables are essentially "storage" for data that you want to pass to your stored procedure. Global and local Declare at the top of the procedure Example @f_name @fullname @Homephone @ext
INSERT CREATE PROCEDURE usp_adduser @login varchar(20), @pswd varchar(20), @f_name varchar(25), @l_name varchar(35), @address_1 varchar(30), @address_2 varchar(30), @city varchar(30), @state char(2), @zipcode char(10), @email varchar(50) AS INSERT INTO USERLIST (login, pswd, f_name, l_name, address_1, address_2, city, state, zipcode, email) VALUES (@login, @pswd, @f_name, @l_name, @address_1, @address_2, @city, @state, @zipcode, @email) exec usp_adduser 'dnelson', 'dean2003', 'Dean', 'Nelson', '200 Berkeley Street', ' ', 'Boston', 'MA', '02116', 'dnelson@test.com'
UPDATE CREATE PROCEDURE usp_updateuser @usr_id int, @login varchar(20), @pswd varchar(20), @f_name varchar(25), @l_name varchar(35), @address_1 varchar(30), @address_2 varchar(30), @city varchar(30), @state char(2), @zipcode char(10), @email varchar(50) AS UPDATE USERLIST SET login=@login, pswd=@pswd, f_name=@f_name, l_name=@l_name, address_1=@address_1, address_2=@address_2, city=@city, state=@state, zipcode=@zipcode, email=@email WHERE usr_id=@usr_id exec usp adduser 1010,'dnelson', 'dean2003', 'Dean', 'Nelson', '200 Berkeley exec usp_adduser 1010, dnelson, dean2003, Dean, Nelson, 200 Berkeley Street', ' ', 'Boston', 'MA', '02116', 'dnelson@test.com'
PASS DATA TO A SELECT STORED PROCEDURE Steps Create header record Create stored procedure name and declare variables Create the rest of your stored procedure /* Name: usp_finduser Description: find a user Author: Tom O Neill Modification Log: Change Description Date Changed By Created procedure 7/15/2003 Tom O Neill */ */ exec usp_finduser 1 CREATE PROCEDURE usp_finduser @usr_id int AS SELECT * FROM USERLIST WHERE usr_id=@usr_id