Postgresql with golang, questions - database

I have created an Api with golang and postgresql as database.
after several requests, the API crashes with an error 500 and a log that displays
pq : sorry , too many customers already
At first it was because I did not close rows when i select, so i have rows.close() all.
But it's not that because i have already this error.
Then saw the launch of the database takes only 3ms, I thought I should start and close the database on every request to reset all connections,
but thinking about it a little more, this is nonsense.
So I ask you, how this error works , is that the client connections are reset after a certain time or connection is cut off until a server reboot for client?
If it resets after a certain time , what are the disadvantages of increasing the maximum number of client connection?
My code:
I open my db like this at start of program :
var gest Gestion
type Gestion struct {
Db *sql.DB
DbLog *sql.DB
}
func InitDbUser() *sql.DB {
dbinfo := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable", DB_USER, DB_PASSWORD, DB_NAME)
db, err := sql.Open("postgres", dbinfo)
LogFatalError(err)
err2 := db.Ping()
LogFatalError(err2)
return db
}
func main() {
gest.Db = InitDbUser()
defer gest.Db.Close()
//routing is here
}
And when i use this request in my psql :
select min_val,max_val from pg_settings where name='max_connections';
I get hat :
min_val | max_val
---------+---------
1 | 8388607
Sorry for my english, i hope you understand what I ask :)

You can check the max_connection setting of PG, that might be the problem here:
select min_val,max_val from pg_settings where name='max_connections'

Related

Do i need to do db.logout() before changing another db password in mongoDB

consider i have two database in mongoDB say db1 and db2 i want to change the password for both initially , do i need to logout db1 before changing db2 password ? or that is not required ? what's the best practice?
current sequence
conn, err := mongo.connect(ctx, connOpts)
//then update the db pass
cmd := bson.D{{"updateUser", dbUserName}, {"pwd", newPass}}
err = client.Database(db1).RunCommand(context.TODO(), command, opts).Decode(&result)
//then logout
err = client.Database(db1).RunCommand(context.TODO(), bson.D{{"logout", 1}}, opts).Decode(&result)
//repeat the same steps again for changing the db2 password
Am I following the right sequence ? whether connecting the db once is enough to do both operation ? is login and logout really required here ?
I'm using go mongo driver .

GO open local postgres connection

My postgres is running locally on Mac on a port 5432
It has database on it named test, and this database has one table in it called test_table
I'm trying to connect to it using GO.
Imports:
"database/sql"
_ "github.com/lib/pq"
Main:
db, err := sql.Open("postgres", "postgres://user:#localhost:5432/test")
if err != nil {
log.Println(err)
}
defer db.Close()
if err2 := db.Ping(); err2 != nil {
fmt.Println("Failed to keep connection alive")
}
db.QueryRow("INSERT INTO test.test_table (name) VALUES (`something`)) RETURNING id").Scan(&id)
fmt.Println(id)
To test the connection I'm running Ping and also try to Insert one line into test_table. But it returns me:
Failed to keep connection alive
0
How can I fix the problem?
In situations like these, it pays to go through the following checklist:
can you connect to the server using the same arguments provided to the go server? I.e. can you run psql -U user -p 5432 -h localhost test ?
are you printing all errors? In the question, err2 should be printed, as it contains critical information about what's going on. Scan also returns an error that is not being saved to a variable or printed. If it were, you might have seen the syntax problem in your query.
can you you run the query in the SQL shell? (psql) If not, fix the query first before continuing.

file is encrypted or is not a database , QT

Sorry for posting this even though there're a few posts about this , but they're not helping.
I'm using sqlite with QT , I wanted to do a simple query but it gives me this error:
file is encrypted or is not a database Unable to execute statement
Some posts' comments say that the DB may be corrupt, I used another program and created a test table from scratch and still has the same problem, this is the code:
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("AdmissionTestDB.sql");
db.open();
if(db.isOpen())
{
QSqlQuery q = db.exec("SELECT * FROM USERS");
if(!q.lastError().isValid())
{
qDebug()<<"works!";
while(q.next())
{
qDebug()<<q.value(8).toString();
}
}
else
qDebug()<<"---db failed to open! , error: "<<q.lastError().text();
db.close();
return true;
}
qDebug()<<"db failed to open! , error: "<<db.lastError().text();
return false;
More Information hopefully it would help solving this:
1- I'm using SQLITE 3
2- The problem happens when I use QSqlQuery q = db.exec("SELECT * FROM USERS"); so the DB actually opens!
3- I used two GUI programs to create the DB one of them is the latest version of SQLiteStudio which is version 3.0.4

Datasnap Delphi XE5 Server side dynamic sql

I am having a small problem with datasnap in delphi Xe5.
I need to run dynamic queries on the server side. I am using an ADO connection on the server methods.
Server Procedure:
var
qryNew: TADOQuery;
dspNew: TDatasetProvider;
begin
qryNew := TADOQuery.Create(nil);
qryNew.Connection := Adoconnection1;
qryNew.SQL.Text := SQL;
qryNew.Name := 'qry'+IntToStr(1);
dspNew := TDatasetProvider.Create(nil);
dspNew.Name := 'dsp'+IntToStr(1);
dspNew.Dataset := qryNew;
qryNew.Open;
Result := dspNew.Name;
end;
Client side procedure:
ClientDataset1.ProviderName :=clientmodule3.ServerMethods1Client.GetDataForClient('Select top 10 * from ODBC.trans_day_2009_1111;');
On the main form i have a SQLconnection, DSProvider connection and a client dataset. When I try to set the provider name for the client with the above code, i get the error "Remote error: Provider not exported : DSP1"
Usually (not always), error messages are helpful if you spend the time to understand them. If it says the provider is not exported, you should have checked why it wasn't - i.e. the doc says:
"To enable the remote data module to pass calls to the provider, the provider's Exported property must be True, and its Owner property must specify the remote data module."
http://docwiki.embarcadero.com/Libraries/XE5/en/Datasnap.Provider.TDataSetProvider
Your provider has no owner.

Error : In fetching data from DatabaseClosed Connection

I am facing a strange problem while running two test-cases that is present in a TestSuite. The Test suite comprises of 15 Test cases, and these two are 9th and 10 th Tc's respectively.
When i am running only these two test cases both are running fine, but with the whole test suite running these two are not present in the report.(Totally getting skipped)
Both the test cases having a function that executes a databases query and fetches a patient name from database and in console we have seen this is the root cause behind the error.
We are facing "Error :In fetching data from Database Io exception: Connection reset"--9th Tc
In fetching data from DatabaseClosed Connection"--10th Tc
The code we have written is below to fetch the patient name:
try
{
stmt =con.createStatement(); //public static java.sql.Statement stmt;public static ResultSet rs;public static Connection con; these 3 we declared in driver script
rs=stmt.executeQuery("select d.id, c.first_name, c.last_name, d.ssn from Table1 d, Table2 c where c.id=d.contact_id and d.facility_id='"+facilityID+"' and d.security_id='"+securityID+"' and <Some condition> and d.id not in (<Some data>);
if (rs.next() == true){
DBFirstName=rs.getString(2);
DBLastName=rs.getString(3);
DBFullName = DBLastName +", " +DBFirstName;
System.out.println("DB Full Name ="+DBFullName);
}else{
System.out.println("Inside else");
return "Fail :Unable to fetch Patient data(lastname) from database";
}
}
catch(Throwable t)
{
APPLICATION_LOGS.debug("Error : In fetching data from Database" +t.getMessage());
System.out.println("Error : In fetching data from Database" +t.getMessage());
}
rs.close();
stmt.close();
Please let me know if anyone having any idea.
Thanks in advance.
Nilanjan.
Please check if database connection has been open . Con.open() might do the work. And also try checking the stack trace i guess it is coming as soon as you start using the connection as it is not open. Please check and tell

Resources