从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数据库的方式有区别吗?如果是,那是什么?有一种方式比另一种更好吗?每种方法有哪些缺点/优点?
答案 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.open
是PG::Connection.new
的别名:
void
init_pg_connection()
{
…
SINGLETON_ALIAS(rb_cPGconn, "open", "new");
…
}
因此,就连接数据库的方式而言,这三者实际上是相同的。 PG.connect
会增加一次额外方法调用的成本,因为它会在内部调用PG::Connection.new
。