DB connection and SQL question - in english and spanish

mi pregunta esta relacionada con la base de datos que uso, que es postgresql, pero quizas mi pregunta aplique a otras bases de datos (no estoy seguro)
para conectarme uso el siguiente codigo, provisto por xojo en el manual de ayuda:

Dim db As New PostgreSQLDatabase db.Host = "192.168.1.172" db.Port = 5432 db.DatabaseName = "BaseballLeague" db.UserName = "broberts" db.Password = "streborb" If db.Connect Then // Use the database Else // There was a database connection error MsgBox(db.ErrorMessage) End If?

lo que quiero hacer es que al abrir mi aplicacion, la misma y unica sesion permanezca activa hasta que mi aplicacion sea cerrada.
quizas el usuario podria dejar la aplicacion abierta muchas horas sin realizar ninguna consulta a la base de datos, quizas todo el fin de semana, y cuando llega el lunes a su trabajo no necesita abrir la aplicacion porque ya lo estaba.
mi pregunta es la siguiente:
1- cuanto tiempo puedo tener abierta una misma sesion sin que la conexion se pierda?
2- si nuevamente ejecuto exactamente el mismo codigo anterior… una nueva sesion en postgresql sera creada o xojo automaticamente reutiliza la misma sesion?
3- xojo crea una nueva sesion cada vez que utilizo db.Connect (por ejemplo para verificar que una sesion siga activa)?
4- cual es la mejor forma de lograr que una misma sesion (o conexion) siga abierta durante mucho tiempo?

my question is related to the database I use, which is postgresql, but maybe my question applies to other databases (I’m not sure)
to connect I use the following code, provided by xojo in the help manual:

Dim db As New PostgreSQLDatabase db.Host = "192.168.1.172" db.Port = 5432 db.DatabaseName = "BaseballLeague" db.UserName = "broberts" db.Password = "streborb" If db.Connect Then // Use the database Else // There was a database connection error MsgBox (db.ErrorMessage) End If

what I want to do is that when I open my application, the same and only session will remain active until my application is closed .
perhaps the user could leave the application open for many hours without making any query to the database, perhaps all weekend, and when he arrives on Monday to work he does not need to open the application because he already was.
My question is this:
1- How long can I have the same session open without the connection being lost?
2 - if again I execute exactly the same previous code … a new session in postgresql will be created or does xojo automatically reuse the same session?
3- xojo creates a new session each time I use [code] db.Connect [/ code] (for example to verify that a session is still active)?
4- What is the best way to keep the same session (or connection) open for a long time?

https://documentation.xojo.com/index.php/Database.Close

este link dice:
this link says:

mi aplicacion es desktop
my application is desktop

It’s worth noting that no one can guarantee that a database connection will stay open. As with any communication over a network, there are things outside your control which can cause a disconnect… and your app needs to be able to handle that.

Nicols,

As Greg stated no one can tell you how long de connection will be available.

You need a strategy to handle database connections, it needs to be available when you need to read or write the database.

Regarding your questions:
1- No one can tell you.
2-It will be a new connection, don’t worry to much about it.
3- It’s your code that creates the code, again you can test if it’s available.
4- Again, don’t worry about it, re-connect again. If your strategy is sane, no memory leak will occur, but it’s up to you.

Hi Nicolas,

There are several ways you can do that. One of these is using a timer to check that the connection still is available. If not, you can reconnect. Another approach is using your own subclass, managing the connection persistence test from there.

On the other hand… there is nothing you can do from the app side if the DDBB is down in the server.

Hay varios enfoques que pueses usar, uno de ellos es el uso de un Timer encargado de verificar que la conexión aun está disponible. En caso contrario, bastaría con reconectar. Otra aproximación consistiría en utilizar tu propia subclase, manejando las pruebas de persistencia de la conexión desde ahí.

Por otra parte, no hay nada que puedas hacer desde la app en el caso de que la BBDD esté caída en el servidor.

Javier

gracias a todos por sus respuestas. se que puede haber problemas de red, firewall y de la misma base de datos. aun asi lo ideal para mi aplicacion es lograr mantener la misma conexion durante el mayor tiempo posible. necesito ingresar dos registros a dos tablas distintas en postgresql, pero leyendo el ID ingresado en la primera, para insertarlo en la segunda. esto lo logro usando currval. es una funcion que proporciona el valor actual de una secuencia. sin embargo primero y por UNICA vez solo al PRINCIPIO de la conexion tengo que usar la funcion nextval. por ejemplo: el valor actual de la secuencia es 25. utilizo nextval y me devuelve 26. hago el insert en la primera tabla y como id es ingresado el valor 26. para insertar ese mismo id en la segunda tabla, utilizo la funcion currval para obtenerlo. si durante la misma sesion quiero hacer un insert, ya no es necesario utilizar nextval. solo hago el insert a la primera tabla y luego el insert en la segunda utilizando currval para obtener el id.
el problema es que si la sesion se abre y cierra permanentemente, permanentemente tengo que usar nextval, por lo que los id de la tabla me quedarian salteados de a dos por ejemplo 25, 27, 29 etc…


Thanks to everyone for your replies. I know there may be problems with the network, firewall and the same database. even so the ideal for my application is to keep the same connection for as long as possible. I need to enter two records into two different tables in postgresql, but reading the ID entered in the first tablr, to insert it in the second table. this is achieved using currval. is a function that provides the current value of a sequence. however I have to use the nextval function ONLY at the beginning of the connection, just one time per session . for example: the current value of the sequence is 25. I use nextval and it returns 26. I insert the first table and as id the value is entered 26. To insert that same id in the second table, I use the currval function to get it. If during the same session I want to make an insert, it is no longer necessary to use nextval. I only do the insert to the first table and then the insert in the second using currval to get the id.
the problem is that if the session opens and closes permanently, permanently I have to use nextval, so the id of the table would be left for two, for example 25, 27, 29 etc.

https://www.postgresql.org/docs/10/static/functions-sequence.html

podria utilizar la funcion RETURNING, pero desconozco como leer los campos devueltos por RETURNING para insertar el ID en la segunda tabla haciendo esto DENTRO DE UN BLOQUE TRANSACCIONAL (“START TRANSACTION”, “COMMIT”)


I could use the RETURNING function, but I do not know how to read the fields returned by RETURNING to insert the ID in the second table doing this INSIDE A TRANSACTIONAL BLOCK (“START TRANSACTION”, “COMMIT”)

https://www.postgresql.org/docs/10/static/dml-returning.html

eso depende de la aplicacion que estes haciendo.
yo tengo una app que es POS y siempre la conecion esta abierta hasta q la app termina.

si la sesion ya esta establecida, abierta y funcionando correctamente… y ejecuto db.connect mi pregunta es: en este caso xojo crea una nueva sesion o utiliza la existente previamente?

Ciao da Italia.
Utilizo una clase de base de datos y un archivo xml para la configuracin.
De esta forma, configuro qu tipo de base de datos usar con los parmetros directamente desde el archivo xml

<?xml version="1.0" encoding="UTF-8"?>
<Configurazione xmlns:xml="http://www.w3.org/XML/1998/namespace">
  <host>127.0.0.1</host>
  <databasetype>MySQL</databasetype>
  <databasename>koalaerp</databasename>
  <username>koalaerp</username>
  <password>koalaerp</password>
  <port>3306</port>
  <portaudp>12345</portaudp> 
</Configurazione>

portaudp es el puerto UDP que uso para leer cdigos de barras con una aplicacin de Android
encuentra la clase para usar db de diferentes tipos aqu

luego usar el db

  If Not app.db.Connected() then
    // error de base de datos no funciona
    exit sub
  else
    if procedure.dbdatabasetype = "MySQL" then app.db.SQLExecute("SET NAMES utf8 COLLATE utf8_general_ci; SET CHARACTER SET utf8")
    Dim sql As String
    sql = "SELECT * from tabella"
    dim rs as recordset
    rs = db.sqlselect(sql)
    .......
   

Hi Nicolas,

If you’re using an existing (still open and working) connection, then you can try to send the command you want to execute… if you get an error, then you can check if this is due to a connection lost… connecting again to it. I mean, you probably don’t want to “connect” again and again against an already open connection.


Si estás usando una conexión existente (abierta y funcional), puedes probar a ejecutar el comando que desees… si obtienes un error, entonces puedes verificar si se debe a una pérdida contra la conexión… conectando de nuevo. Es decir, probablemente no quieras (o debas) “conectar” una y otra vez contra una conexión ya establecida.

Javier

despues de investigar las distintas opciones voy a crear una nueva sesion solo si la BD se ha desconectado. ademas, he descubierto que el insert genera implicitamente un nextval. gracias a todos por sus excelentes ideas