Create a Simple JDBC App


Download and Install Spring Tool Suite

http://www.springsource.org/sts

Create a Maven Project

Run Spring Tool Suite

New -> Maven -> Maven Project

Select the default quickstart archetype

org.apache.maven.archetypes maven-archetype-quickstart

Enter a Group Id and Artifact Id for the app:

Group Id: com.skills421.jdbc

Artifact Id: jdbcExample

Edit Pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.skills421.jpa</groupId>
<artifactId>jdbcExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>jdbcExample</name>
<url>http://maven.apache.org</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.2-1002.jdbc4</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>java.net</id>
<url>http://jdbc.postgresql.org/download/postgresql-9.2-1002.jdbc4.jar</url>
</repository>
</repositories>
</project>

Edit App.java

package com.skills421.jpa.jdbcExample;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
throws ClassNotFoundException, SQLException
{
Class.forName("org.postgresql.Driver");

String url = "jdbc:postgresql://localhost/jdtest";
Properties props = new Properties();
props.setProperty("user","john");
props.setProperty("password”,”secret”);
//props.setProperty("ssl","false");

Connection conn = DriverManager.getConnection(url, props);

// make sure autocommit is off
conn.setAutoCommit(false);

Statement st = conn.createStatement();

// Turn use of the cursor on.
st.setFetchSize(50);

ResultSet rs = st.executeQuery("SELECT * FROM person);

ResultSetMetaData rsmd = rs.getMetaData();

while (rs.next())
{
for(int i=1; i <= rsmd.getColumnCount(); i++)
{
System.out.println(rsmd.getColumnName(i) + " = " + rs.getObject(i));
}
}

rs.close();
}
}

Run App.java

name = John Dunning
age = 21
height = 1.80

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Up ↑

%d bloggers like this: