Connecting to the MySQL Server, Selecting a Database, and Disconnecting
Problem
You need to establish a connection to the server to access a database, and to shut down the connection when you’re done.
Solution
Each API provides functions for connecting and disconnecting. The connection routines require that you provide parameters specifying the MySQL user account you want to use. You can also specify a database to use. Some APIs allow this at connection time; others require a separate call after connecting.
Discussion
The programs in this section show how to perform three fundamental operations that are common to the vast majority of MySQL programs:
Establishing a connection to the MySQL server.
Every program that uses MySQL does this, no matter which API you use. The details on specifying connection parameters vary between APIs, and some APIs provide more flexibility than others. However, there are many common elements. For example, you must specify the host where the server is running, as well as the name and password for the MySQL account that you’re using to access the server.
Selecting a database.
Most MySQL programs select a database, either when they connect to the server or immediately thereafter.
Disconnecting from the server
Each API provides a means of shutting down an open connection. It’s best to close the connection as soon as you’re done with the server so that it can free up any resources that are allocated to servicing the connection. Otherwise, if your program performs ...
Get MySQL Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.