Ruby中的`PG.connect`和`PG :: Connection.open`有什么区别?''宝石?

时间:2016-03-04 00:06:03

标签: ruby pg

pg module doc开始,似乎连接到PG db的正确方法是使用:

public class User extends RealmObject {

    @PrimaryKey
    private String id;
    private String firstName;
    private String lastName;
    private int age;

public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

public String getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

In Your activity, You can store values to the Realm object like below,

User user = new User()
user.setFirstName("John")
user.setLastName("Kennedy")
user.setAge(40)

Realm realm = Realm.getInstance(this)
realm.executeTransaction {
                realm.copyToRealmOrUpdate(user)
            }
//Below is written in Kotlin language. You can find similar one in Java from the link given
val userJohn: User = realm.where(User::class.java)?.equalTo("firstName", "John").findFirst()

//Values of User John can be accessed like below
println(userJohn.firstName)
println(userJohn.lastName)
println(userJohn.age)

但是,我在网上找到other examples代替使用conn = PG::Connection.open(dbname: 'test') 方法:

PG.connect

这两种连接postgresql数据库的方式有区别吗?如果是,那是什么?有一种方式比另一种更好吗?每种方法有哪些缺点/优点?

1 个答案:

答案 0 :(得分:2)

documentation for the PG module itself,您可以看到PG.connect是"便利别名" PG::Connection.new

def self::connect( *args )
  return PG::Connection.new( *args )
end

source code of PG::Connection开始,我们也清楚PG::Connection.openPG::Connection.new的别名:

void
init_pg_connection()
{
    …
    SINGLETON_ALIAS(rb_cPGconn, "open", "new");
    …
}

因此,就连接数据库的方式而言,这三者实际上是相同的。 PG.connect会增加一次额外方法调用的成本,因为它会在内部调用PG::Connection.new