Java Connection PostgreSQL

Source: Internet
Author: User
Tags postgresql postgres database

Recently the company with PostgreSQL this database, see online said this database is still good, I used a bit, I was using Java to connect a database.

In fact, each database is connected in roughly the same way, only with different drivers, with different databases only need to change the database driver package.

Project Structure

Code

DBHelper

 PackageCom.xxx.postgrepsql;Importjava.sql.Connection;ImportJava.sql.DriverManager;Importjava.sql.PreparedStatement;/*** Database Helper class*/ Public classDBHelper {Private StaticString url = "Jdbc:postgresql://localhost:5432/solution"; Private StaticString Driver = "Org.postgresql.Driver"; Private StaticString user = "Postgres"; Private StaticString password = "18731362155"; PrivateConnection Connection =NULL;  PublicConnection getconnection () {returnconnection; }     PublicPreparedStatement getstatement () {returnstatement; }    PrivatePreparedStatement statement =NULL;  Publicdbhelper (String sql) {Try{class.forname (driver); Connection=drivermanager.getconnection (URL, user, password); Statement=connection.preparestatement (SQL); } Catch(Exception e) {e.printstacktrace (); }    }     Public voidClose () {Try {             This. Connection.close ();  This. Statement.close (); } Catch(Exception e) {e.printstacktrace (); }    }}

Jdbcdemo

 PackageCom.xxx.postgrepsql;ImportJava.sql.*;/*** Connect Postgres database*/ Public classJdbcdemo { Public Static voidMain (string[] args) {String SQL= "SELECT * FROM T_user"; DBHelper DBHelper=Newdbhelper (SQL); Try{ResultSet ResultSet=dbhelper.getstatement (). ExecuteQuery (); System.out.println ("Id username Password");  while(Resultset.next ()) {System.out.println (resultset.getstring (1) + "" "+resultset.getstring (2) +" "+resultset.getstring (3));        } dbhelper.close (); } Catch(SQLException e) {dbhelper.close ();        E.printstacktrace (); }    }}

If you have any questions, please contact qq1058179540.

Java Connection PostgreSQL

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.