Connecting to a Database
Connecting to a database is the first step in developing an application using libpq. In this case, you can use functions, such as PQconnectdb and PQsetdbLogin, to connect to the database server. These functions return a connection object. You need to save the connection object for subsequent database operations.
The following uses the development source program testlibpq.c as an example (for details about the complete example, see Establishing a Database Connection, Executing SQL Statements, and Returning Results).
/* * Note: The source program testlibpq.c provides basic and common application scenarios of libpq. * The PQconnectdb, PQexec, PQntuples, and PQfinish APIs provided by libpq are used to establish database connections, execute SQL statements, obtain returned results, and clear resources. * Header file. For details about user-defined functions, see the complete example. */ /* The values of variables such as user and passwd must be read from environment variables or configuration files. Environment variables need to be configured as required. If no environment variable is used, a character string can be directly assigned. */ const char conninfo[1024]; PGconn *conn; PGresult *res; int nFields; int i,j; char *passwd = getenv("EXAMPLE_PASSWD_ENV"); char *port = getenv("EXAMPLE_PORT_ENV"); char *host = getenv("EXAMPLE_HOST_ENV"); char *username = getenv("EXAMPLE_USERNAME_ENV"); char *dbname = getenv("EXAMPLE_DBNAME_ENV"); /* * This value is used when the user provides the value of the conninfo character string in the command line. * Otherwise, the environment variables or all other connection parameters * use the default values. */ if (argc > 1) strcpy(conninfo, argv[1]); else sprintf(conninfo, "dbname=%s port=%s host=%s application_name=test connect_timeout=5 sslmode=allow user=%s password=%s", dbname, port, host, username, passwd); /* Connect to the database. */ conn = PQconnectdb(conninfo); /* Check whether the backend connection has been successfully established. */ if (PQstatus(conn) != CONNECTION_OK) { fprintf(stderr, "Connection to database failed: %s", PQerrorMessage(conn)); exit_nicely(conn); }
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot