Sunteți pe pagina 1din 3

Tutorial for JDBC Connection to PostgreSQL

1. Download JDBC driver for Postgresql from: http://jdbc.postgresql.org/download.html 2. Load the JDBC Driver in Java file a. Create a java file named ExampleJdbc.java b. The following line of code loads the JDBC driver for PostgreSQL Class.forName("org.postgresql.Driver"); 3. Establish connectivity via Java: a. Import following package in your code which handles JDBC connection import java.sql.* b. Following piece of code connects to the database named testdb on localhost machine with username user1 and password xyz. Connection connection = DriverManager.getConnection( "jdbc:postgresql://localhost/testdb", "user1", "xyz"); c. Instead of localhost, use the ip address of machine on which the database resides. 4. Run sql queries a. You first need to create a statement to run sql queries Statement st = connection.createStatement(); b. You can use st to execute queries. 5. Create a table a. Following piece of code creates a table called actor String sql = "insert into actor (name, dob, address) values ('Priyanka Chopra', '1980-1-25', 'India'); st.executeUpdate(sql);

b. The function executeUpdate() is used to execute an sql query that does not return anything e.g. create, insert, delete and update 6. Insert into the table a. Following code snippet inserts two rows one by one into the table actor we created previously sql = "insert into actor (name, dob, address) values ('Priyanka Chopra', '19801-25', 'India')"; st.executeUpdate(sql); sql = "insert into actor values ('Tom Cruise', '1965-4-20', 'USA')"; st.executeUpdate(sql); 7. Run select query a. Following code snippet prints the two rows we inserted previously sql = "select * from actor"; ResultSet result = st.executeQuery(sql); if (result != null) { while (result.next()) { System.out.println("name = " + result.getString("name")+ " dob = " + result.getString("dob") + " address = " + result.getString("address")); } } result.close(); b. The function executeQuery() is used to execute an sql query that returns results e.g. select 8. Disconnect from database a. After queries are over, we can disconnect from database using following code st.close(); connection.close(); 9. Compile and run the program a. Assume ExampleJdbc.java is at location LOC b. Compile program

javac ExampleJdbc.java c. Run it. Include JDBC driver .jar file which you downloaded. Assume that .jar file is also at location LOC java -cp LOC\postgresql-9.1-901.jdbc4.jar;LOC ExampleJdbc

S-ar putea să vă placă și