UNIDAD 7: INTRODUCION A LAS BASES DE DATOS

TEMA LINUX GCC 6: FUNCIONES MYSQL

Mysql es un servidor de bases de datos muy rico en funciones, instrucciones y objetos, muchos de las cuales se estaran usando a lo largo de los programas en esta unidad.

Las principales funciones que se usarón son:

1.- MYSQL estructura; → se usa para crear una estructura que contendra la coneccion o enlaze entre el programa cliente y el servidor msql.

2.- MYSQL_RES *resultset; → crea una estructura que almacena los renglones de la tabla en disco que fueron regresados por instrucciones sql= select, show, describe, explain, en particular resultset es una tabla virtual en la memoria de la tabla fisica en disco.

3.- MYSQL_ROW renglon; → es una estructura que contiene un solo renglon de la tabla contenida en el resultset, renglón que se cargara usando la instrucción(nota 4):

4.- mysql_fetch_row(); → ver nota 3

5.- mysql_init(); → Inicializa el objeto enlaze o coneccion, recordar que este objeto de enlaze o conección primero se debera crear de la manera descrita en la nota 1.

6.- mysql_real_connect (&objcon, “servidor”, “usuario”, “password”, “basedatos”, 0, NULL, 0);

La instrucción mas importante, realiza el enlaze o conección entre el programa y el servidor sql, sus ocho parametros son:

6.1.- el objeto coneccion ver notas 1 y 5.

6.2.- la direccion internet del servidor de bases de datos mysql.

6.3.- el nombre del usuario de la cuenta de mysql.

6.4.- el password del usuario de la cuenta de mysql.

6.5.- el nombre de la base de datos que se va a usar.

6.6.- el puerto tcp/ip a usar, 0 es default.

6.7.- el socket de unix a usar, NULL es default

6.8.- bandera, semaforo del cliente, puede ser 0(default) o alguna de las siguientes combinaciones, CLIENT_COMPRESS, CLIENT_FOUND_ROWS, CLIENT_IGNORE_SPACE , CLIENT_INTERACTIVE, CLIENT_NO_SCHEMA, CLIENT_ODBC, CLIENT_SSL.

7.- mysql_query(&objcon,query); → instrución mas usada se usa para mandar instrucciónes sql a la base de datos.

8.- mysql_store_result(&objcon); → despues de mysql_query(), se debera usar esta instrucción para almacenar el resultset (la tabla virtual en memoria que es la copia de la tabla real en disco), recordar ademas que esta instruccion se usara solamente cuando se manda a la base de datos instrucciones sql que regresan datos, tales como select, show, etc, no usarla para insert, delete, update.

9.- mysql_num_rows(resultset); → se usa para conocer la cantidad de renglones que contiene un resultset.

10.- mysql_free_result(resultset); → usar al final del programa para liberar al servidor del resultset que tiene almacenado en memoria, recordar que si no se usa esta instrucción en todos tus programas el servidor de mysql se ira degradando lentamente hasta que se tenga que resetear.

11.- mysql_close(&objcon); → ultima instruccion del programa se usa para cerrar el enlaze o conección entre programa y servidor.

SIN EMBARGO ES IMPORTANTE CONOCER QUE MYSQL TIENE TAMBIEN LAS SIGUIENTES FUNCIONES MYSQL QUE PUEDEN USAR EN SUS PROGRAMAS.

mysql_affected_rows() Returns the number of rows changed/deleted/inserted by the last UPDATE, DELETE, or INSERT query.

mysql_change_user() Changes user and database on an open connection.

mysql_character_set_name() Returns the name of the default character set for the connection.

mysql_close() Closes a server connection.

mysql_connect() Connects to a MySQL server. This function is deprecated; use mysql_real_connect() instead.

mysql_create_db() Creates a database. This function is deprecated; use the SQL command CREATE DATABASE instead.

mysql_data_seek() Seeks to an arbitrary row in a query result set.

mysql_debug() Does a DBUG_PUSH with the given string.

mysql_drop_db() Drops a database. This function is deprecated; use the SQL command DROP DATABASE instead.

mysql_dump_debug_info() Makes the server write debug information to the log.

mysql_eof() Determines whether the last row of a result set has been read. This function is deprecated; mysql_errno() or mysql_error() may be used instead.

mysql_errno() Returns the error number for the most recently invoked MySQL function.

mysql_error() Returns the error message for the most recently invoked MySQL function.

mysql_escape_string() Escapes special characters in a string for use in a SQL statement.

mysql_fetch_field() Returns the type of the next table field.

mysql_fetch_field_direct() Returns the type of a table field, given a field number.

mysql_fetch_fields() Returns an array of all field structures.

mysql_fetch_lengths() Returns the lengths of all columns in the current row.

mysql_fetch_row() Fetches the next row from the result set.

mysql_field_seek() Puts the column cursor on a specified column.

mysql_field_count() Returns the number of result columns for the most recent query.

mysql_field_tell() Returns the position of the field cursor used for the last mysql_fetch_field().

mysql_free_result() Frees memory used by a result set.

mysql_get_client_info() Returns client version information.

mysql_get_host_info() Returns a string describing the connection.

mysql_get_proto_info() Returns the protocol version used by the connection.

mysql_get_server_info() Returns the server version number.

mysql_info() Returns information about the most recently executed query.

mysql_init() Gets or initialises a MYSQL structure.

mysql_insert_id() Returns the ID generated for an AUTO_INCREMENT column by the previous query.

mysql_kill() Kills a given thread.

mysql_list_dbs() Returns database names matching a simple regular expression.

mysql_list_fields() Returns field names matching a simple regular expression.

mysql_list_processes() Returns a list of the current server threads.

mysql_list_tables() Returns table names matching a simple regular expression.

mysql_num_fields() Returns the number of columns in a result set.

mysql_num_rows() Returns the number of rows in a result set.

mysql_options() Sets connect options for mysql_connect().

mysql_ping() Checks whether the connection to the server is working, reconnecting as necessary.

mysql_query() Executes a SQL query specified as a null-terminated string.

mysql_real_connect() Connects to a MySQL server.

mysql_real_escape_string() Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection.

mysql_real_query() Executes a SQL query specified as a counted string.

mysql_reload() Tells the server to reload the grant tables.

mysql_row_seek() Seeks to a row in a result set, using value returned from mysql_row_tell().

mysql_row_tell() Returns the row cursor position.

mysql_select_db() Selects a database.

mysql_shutdown() Shuts down the database server.

mysql_stat() Returns the server status as a string.

mysql_store_result() Retrieves a complete result set to the client.

mysql_thread_id() Returns the current thread ID.

mysql_thread_safe()

To connect to the server, call mysql_init() to initialise a connection handler, then call mysql_real_connect() with that handler (along with other information such as the hostname, user name, and password). Upon connection, mysql_real_connect() sets the reconnect flag (part of the MYSQL structure) to a value of 1. This flag indicates, in the event that a query cannot be performed because of a lost connection, to try reconnecting to the server before giving up. When you are done with the connection, call mysql_close() to terminate it.

While a connection is active, the client may send SQL queries to the server using mysql_query() or mysql_real_query(). The difference between the two is that mysql_query() expects the query to be specified as a null-terminated string whereas mysql_real_query() expects a counted string. If the string contains binary data (which may include null bytes), you must use mysql_real_query().

For each non-SELECT query (for example, INSERT, UPDATE, DELETE), you can find out how many rows were changed (affected) by calling mysql_affected_rows().

For SELECT queries, you retrieve the selected rows as a result set. (Note that some statements are SELECT-like in that they return rows. These include SHOW, DESCRIBE, and EXPLAIN. They should be treated the same way as SELECT statements.)

There are two ways for a client to process result sets. One way is to retrieve the entire result set all at once by calling mysql_store_result(). This function acquires from the server all the rows returned by the query and stores them in the client. The second way is for the client to initiate a row-by-row result set retrieval by calling mysql_use_result(). This function initialises the retrieval, but does not actually get any rows from the server.

In both cases, you access rows by calling mysql_fetch_row(). With mysql_store_result(), mysql_fetch_row() accesses rows that have already been fetched from the server. With mysql_use_result(), mysql_fetch_row() actually retrieves the row from the server. Information about the size of the data in each row is available by calling mysql_fetch_lengths().

After you are done with a result set, call mysql_free_result() to free the memory used for it.

The two retrieval mechanisms are complementary. Client programs should choose the approach that is most appropriate for their requirements. In practice, clients tend to use mysql_store_result() more commonly.

An advantage of mysql_store_result() is that because the rows have all been fetched to the client, you not only can access rows sequentially, you can move back and forth in the result set using mysql_data_seek() or mysql_row_seek() to change the current row position within the result set. You can also find out how many rows there are by calling mysql_num_rows(). On the other hand, the memory requirements for mysql_store_result() may be very high for large result sets and you are more likely to encounter out-of-memory conditions.

An advantage of mysql_use_result() is that the client requires less memory for the result set because it maintains only one row at a time (and because there is less allocation overhead, mysql_use_result() can be faster). Disadvantages are that you must process each row quickly to avoid tying up the server, you don't have random access to rows within the result set (you can only access rows sequentially), and you don't know how many rows are in the result set until you have retrieved them all. Furthermore, you must retrieve all the rows even if you determine in mid-retrieval that you've found the information you were looking for.

The API makes it possible for clients to respond appropriately to queries (retrieving rows only as necessary) without knowing whether or not the query is a SELECT. You can do this by calling mysql_store_result() after each mysql_query() (or mysql_real_query()). If the result set call succeeds, the query was a SELECT and you can read the rows. If the result set call fails, call mysql_field_count() to determine whether a result was actually to be expected. If mysql_field_count() returns zero, the query returned no data (indicating that it was an INSERT, UPDATE, DELETE, etc.), and was not expected to return rows. If mysql_field_count() is non-zero, the query should have returned rows, but didn't. This indicates that the query was a SELECT that failed. See the description for mysql_field_count() for an example of how this can be done.

Both mysql_store_result() and mysql_use_result() allow you to obtain information about the fields that make up the result set (the number of fields, their names and types, etc.). You can access field information sequentially within the row by calling mysql_fetch_field() repeatedly, or by field number within the row by calling mysql_fetch_field_direct(). The current field cursor position may be changed by calling mysql_field_seek(). Setting the field cursor affects subsequent calls to mysql_fetch_field(). You can also get information for fields all at once by calling mysql_fetch_fields().

For detecting and reporting errors, MySQL provides access to error information by means of the mysql_errno() and mysql_error() functions. These return the error code or error message for the most recently invoked function that can succeed or fail, allowing you to determine when an error occurred and what it was.

MySQL Reference Manual (C) 2002 MySQL AB

Politica de Privacidad