如果没有安装postgresql,可参照此文安装,配置,并启动:http://blog.youkuaiyun.com/qiaoning13256/article/details/7225709
Postgresql jdbc下载地址:http://jdbc.postgresql.org/download.html
Importing the driver:
- Right click on your prject
- Choose property
- Choose Java build path
- Choose add external JARS.. and select the location to the JDBC driver
Java代码:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Main { public static void main(String args[]){ try { Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } String url = "jdbc:postgresql://127.0.0.1/mydb"; Connection conn = null; try { conn = DriverManager.getConnection(url, "qn", ""); } catch (SQLException e) { e.printStackTrace(); } Statement stat = null; try { stat = conn.createStatement(); } catch (SQLException e) { e.printStackTrace(); } String sqlTemplate = "select * from userinfo where username = '%s' and password = '%s'"; String sqlsel = String.format(sqlTemplate, "qiaoning", "hello"); ResultSet resultSet = null; try { resultSet = stat.executeQuery(sqlsel); } catch (SQLException e) { e.printStackTrace(); } try { while(resultSet.next()){ System.out.println(resultSet.getString(1)); System.out.println(resultSet.getString(2)); } } catch (SQLException e) { e.printStackTrace(); } } }