Upload
others
View
18
Download
0
Embed Size (px)
Citation preview
COP4540
P R O F E S S O R : D R S H U - C H I N G C H E N S
TUTORIALT A : H S I N - Y U H A
OUTLINEOUTLINE
• Postgresql installation• Postgresql installation• Introduction of JDBC• Stored ProcedureStored Procedure
POSTGRES INSTALLATION (1)POSTGRES INSTALLATION (1)
• Extract the source file• Extract the source file
• Start the configuration (about one minute)• Set up the prefix as the folder with your own permission
Defa lt o ld be home director• Default would be home directory.
POSTGRES INSTALLATION (2)POSTGRES INSTALLATION (2)
• Compile all of your source code• Compile all of your source code
• If the code was built correctly the last line would beIf the code was built correctly the last line would be
• Ready to install (less than one minute)
• Successfully install
POSTGRES INSTALLATION (3)POSTGRES INSTALLATION (3)
• Initialize database cluster• Initialize database cluster
• Start the postgres server
OUTLINEOUTLINE
• Postgresql installation• Postgresql installation• Introduction of JDBC• Stored ProcedureStored Procedure
JDBCJDBC
• Write once Match all DBMS!!• Write once, Match all DBMS!!• The Java Database connectivity
• Making a connection to a databaseg• Creating SQL or MySQL statements• Executing queries in the database• Viewing or Modifying the result records• Viewing or Modifying the result records
Oracle JDBC Driver
Oracle Database
ApplicationJDBCDriver
Interface
SQL JDBC Driver
MySQL JDBC Driver
SQL Database
MySQL Database
PostgreSQLJDBC Driver
Database
PostgreSQLDatabase
STEPS OF CONNECTING DATABASESTEPS OF CONNECTING DATABASE
1) Get the specific type of JDBC driver1) Get the specific type of JDBC driver2) Initializing the Driver3) Start the Connection3) Start the Connection4) Initialize one Statement object5) Send out the SQL execute*()6) Get the Resultset object which is returned by
DBMS7) Cl th ti l ()7) Close the connection close()
(1) GET JDBC DRIVER(1) GET JDBC DRIVER
• Download driver from any DBMS company website• Download driver from any DBMS company website• Format: <DBMS_Name-JDBC-Type_n.jar>
• For example: postgresql-9.0-801.jdbc4.jarp p g q j j• Put it to any accessible library folder• PostgreSQL JDBC Driver : http://jdbc.postgresql.org
(2) INITIALIZING THE DRIVER (2) INITIALIZING THE DRIVER
• Importing JDBC• Importing JDBC• Import java.sql.*
• Loading the serverg• Class.forName("org.postgresql.Driver");
try {Cl f N (" t l D i ")Class.forName("org.postgresql.Driver");} catch (ClassNotFoundException e) {System.out.println(“Can’t find Driver class ");}}
(3) START THE CONNECTION(3) START THE CONNECTION
• String DRIVER = "org postgresql Driver";• String DRIVER = org.postgresql.Driver ;String URL ="jdbc:postgresql://[IP]:5432/[DB_Name]";String USER = "whoami";String PASSWORD = "123456";
Connection conn =DriverManager getConnection( URL USER PASSWORD );DriverManager.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 OBJECTAND (5)EXECUTE
• 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 Use get<Type>() to retrieve the data by attribute name or
order
EXECUTE EXAMPLEEXECUTE EXAMPLE
• Create / Update table• Create / Update table
Statements stmt = conn.createStatement( );stmt.executeUpdate(stmt.executeUpdate("CREATE TABLE jdemo ( title character varying(50),body text, id serial)");stmt.executeUpdate(“ALTER TABLE jdemo ADD PRIMARY KEY (id)”);
• View dataResultSet result =stmt executeQuery(“SELECT * FROM jdemo”);stmt.executeQuery( SELECT FROM jdemo );while (result.next( )) {
System.out.print(result.getInt(“id”) + “\t”);System.out.print(result.getString("title") + "\t");
i ( i ( ))System.out.println(result.getString("body"));}
JDBC EXAMPLEJDBC 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. }
OUTLINEOUTLINE
• Postgresql installation• Postgresql installation• Introduction of JDBC• Stored ProcedureStored Procedure
WHAT ARE STORED PROCEDURESWHAT ARE STORED PROCEDURES
• A stored procedure is an already written SQL• A stored procedure is an already written SQLstatement that is saved in the database.
• Advantageg• Reduce roundtrips across the network• Can make security easier to manage• Are precompiled• Are precompiled
STORED PROCEDURES - SQLSTORED PROCEDURES - SQL
• How to run a stored procedures• How to run a stored procedures
• The SQL language inside the stored procedureexec usp_displayallusers
The SQL language inside the stored procedureSELECT * FROM USERLIST
• How to start with writing stored procedure• A database management system
A database b ilt inside the database management s stem• A database built inside the database management system• A text editor
FIRST STORED PROCEDUREFIRST STORED PROCEDURE
/*/*Name: usp_displayallusersDescription: displays all records and columns in USERLIST tableAuthor: Tom O’NeillModification Log: ChangeDescription Date Changed ByCreated procedure 7/15/2003 Tom O’Neill*/*/
CREATE PROCEDURE usp_displayallusersASSELECT * FROM USERLIST
INPUT VARIABLESINPUT VARIABLES
• Input variables are essentially "storage" for data that • 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• @Homephonep• @ext
INSERTINSERT
CREATE PROCEDURE usp adduserCREATE PROCEDURE usp_adduser@login varchar(20),@pswd varchar(20),@f_name varchar(25),@l name varchar(35),@l_name varchar(35),@address_1 varchar(30),@address_2 varchar(30),@city varchar(30),@state char(2),@state char(2),@zipcode char(10),@email varchar(50)ASINSERT INTO USERLIST (login, pswd, f name, l name, address 1, address 2, city, 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', '[email protected]'
UPDATEUPDATE
• AS
CREATE PROCEDURE usp_updateuser@usr_id int,@login varchar(20),
• AS• UPDATE USERLIST• SET• login=@login,
pswd=@pswd@pswd varchar(20),@f_name varchar(25),@l_name varchar(35),@address_1 varchar(30),@address 2 varchar(30),
pswd=@pswd,f_name=@f_name,l_name=@l_name,address_1=@address_1,address_2=@address_2,@address_2 varchar(30),
@city varchar(30),@state char(2),@zipcode char(10),@email varchar(50)
city=@city,state=@state,zipcode=@zipcode,email=@email
• WHERE usr id=@usr id• 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', '[email protected]'
PASS DATA TO A SELECT STORED PROCEDURE
• Steps• Steps• Create header record• Create stored procedure name and declare variables• Create the rest of your stored procedure/*Name: usp_finduserDescription: find a userDescription: find a userAuthor: Tom O’NeillModification Log: ChangeDescription Date Changed ByCreated procedure 7/15/2003 Tom O’Neill*/ fi d ‘1’*/
CREATE PROCEDURE usp_finduser@usr_id intAS
exec usp_finduser ‘1’
SSELECT * FROM USERLISTWHERE usr_id=@usr_id