首页 > 代码库 > Java简单的数据库连接

Java简单的数据库连接

package test.postgre;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class SimpleJdbc {

    public static void main(String[] args){
        Connection conn = getConn();
        String sql = "select * from calendar";
        Statement stmt = null;
        ResultSet rs = null;
        try {
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            while(rs.next()){
                System.out.println(rs.getInt(1));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    /**
     * database line
     * @return
     */
    public static Connection getConn(){
        Connection conn = null;
        try {
            Class.forName("org.postgresql.Driver");
            String url="jdbc:postgresql://***.**.**.**/test";
            try {
                conn = DriverManager.getConnection(url, "postgres", "postgres");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return conn;
    }
}

 

Java简单的数据库连接