L'API de C de MySQL
Salta a la navegació
Salta a la cerca
Contingut
Exemple lenguatge C
$ sudo apt-get install libmysqlclient-dev
referència de les funcions:
$ gcc mysqltest.c -o mysqltest -lmysqlclient
//http://www.dscripts.net/2010/06/11/how-to-connect-to-mysql-database-using-ansi-c-language/ //gcc mysqltest.c -o mysqltest -lmysqlclient //??? //paquets necessaris: libmysqlclient-dev,libmysqld-dev. I també libwrap0-dev #include<stdio.h> #include<mysql/mysql.h> #include<stdlib.h> int main(int argc, char *argv[]) { MYSQL *conn; MYSQL_RES *res; MYSQL_ROW row; char *server ="localhost"; char *user = "root"; char *password = "isistot09"; char *database = "openbravopos"; conn = mysql_init(NULL); // Connect to database if(!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) { fprintf(stderr, "%s\n", mysql_error(conn)); exit(1); } // sql query if(mysql_query(conn, "select * from PEOPLE")) { fprintf(stderr, "%s\n", mysql_error(conn)); exit(1); } res = mysql_use_result(conn); //output table name printf("Mysql Tables in mysql database: \n"); while((row = mysql_fetch_row(res)) !=NULL) printf("%-3s%-30s%-30s\n", row[0], row[1], row[2]); //inserir una fila if(mysql_query(conn, "INSERT INTO PEOPLE(ID, NAME, ROLE) VALUES(4,'Joan',0)")) { fprintf(stderr, "%s\n", mysql_error(conn)); exit(1); } // close connection mysql_free_result(res); mysql_close(conn); return 0; }
Exemple llenguatge C++
g++ -o testMySqlAPI testMySqlAPI.cpp `mysql_config --cflags` `mysql_config --libs`
//http://www.yolinux.com/TUTORIALS/MySQL-Programming-C-API.html#INSERT_SELECT //g++ -o testMySqlAPI testMySqlAPI.cpp `mysql_config --cflags` `mysql_config --libs` /* CREATE DATABASE bedrock; USE bedrock; CREATE TABLE employee (IDpk integer NOT NULL auto_increment, Employee_Name char(20), Dept char(20), JobTitle char(20), PRIMARY KEY (IDpk)); INSERT INTO employee (Employee_Name,Dept,JobTitle) VALUES ('Fred Flinstone','Worker','Rock Digger'); INSERT INTO employee (Employee_Name,Dept,JobTitle) VALUES ('Wilma Flinstone','Finance','Analyst'); INSERT into employee (Employee_Name,Dept,JobTitle) VALUES ('Barney Rubble','Sales','Neighbor'); */ #include <stdio.h> #include <mysql.h> #include <string> class FFError { public: std::string Label; FFError( ) { Label = (char *)"Generic Error"; } FFError( char *message ) { Label = message; } ~FFError() { } inline const char* GetMessage ( void ) { return Label.c_str(); } }; using namespace std; main() { // -------------------------------------------------------------------- // Connect to the database MYSQL *MySQLConRet; MYSQL *MySQLConnection = NULL; string hostName = "localhost"; string userId = "root"; string password = "isistot09"; string DB = "bedrock"; MySQLConnection = mysql_init( NULL ); try { MySQLConRet = mysql_real_connect( MySQLConnection, hostName.c_str(), userId.c_str(), password.c_str(), DB.c_str(), 0, NULL, 0 ); if ( MySQLConRet == NULL ) throw FFError( (char*) mysql_error(MySQLConnection) ); printf("MySQL Connection Info: %s \n", mysql_get_host_info(MySQLConnection)); printf("MySQL Client Info: %s \n", mysql_get_client_info()); printf("MySQL Server Info: %s \n", mysql_get_server_info(MySQLConnection)); } catch ( FFError e ) { printf("%s\n",e.Label.c_str()); return 1; } int mysqlStatus = 0; MYSQL_RES *mysqlResult = NULL; // -------------------------------------------------------------------- // This block of code would be performed if this insert were in a loop // with changing data. Of course it is not necessary in this example. if(mysqlResult) { mysql_free_result(mysqlResult); mysqlResult = NULL; } // -------------------------------------------------------------------- // Perform a SQL INSERT try { string sqlInsStatement = "INSERT INTO employee (Employee_Name,Dept,JobTitle) VALUES ('Betty Rubble','IT','Neighbor')"; mysqlStatus = mysql_query( MySQLConnection, sqlInsStatement.c_str() ); if (mysqlStatus) { throw FFError( (char*)mysql_error(MySQLConnection) ); } } catch ( FFError e ) { printf("%s\n",e.Label.c_str()); mysql_close(MySQLConnection); return 1; } if(mysqlResult) { mysql_free_result(mysqlResult); mysqlResult = NULL; } // -------------------------------------------------------------------- // Perform a SQL SELECT and retrieve data MYSQL_ROW mysqlRow; MYSQL_FIELD *mysqlFields; my_ulonglong numRows; unsigned int numFields; try { string sqlSelStatement = "SELECT * FROM employee"; mysqlStatus = mysql_query( MySQLConnection, sqlSelStatement.c_str() ); if (mysqlStatus) throw FFError( (char*)mysql_error(MySQLConnection) ); else mysqlResult = mysql_store_result(MySQLConnection); // Get the Result Set if (mysqlResult) // there are rows { // # of rows in the result set numRows = mysql_num_rows(mysqlResult); // # of Columns (mFields) in the latest results set numFields = mysql_field_count(MySQLConnection); // Returns the number of columns in a result set specified numFields = mysql_num_fields(mysqlResult); printf("Number of rows=%u Number of fields=%u \n",numRows,numFields); } else { printf("Result set is empty"); } // Print column headers mysqlFields = mysql_fetch_fields(mysqlResult); for(int jj=0; jj < numFields; jj++) { printf("%s\t",mysqlFields[jj].name); } printf("\n"); // print query results while(mysqlRow = mysql_fetch_row(mysqlResult)) // row pointer in the result set { for(int ii=0; ii < numFields; ii++) { printf("%s\t", mysqlRow[ii] ? mysqlRow[ii] : "NULL"); // Not NULL then print } printf("\n"); } if(mysqlResult) { mysql_free_result(mysqlResult); mysqlResult = NULL; } } catch ( FFError e ) { printf("%s\n",e.Label.c_str()); mysql_close(MySQLConnection); return 1; } // -------------------------------------------------------------------- // Close datbase connection mysql_close(MySQLConnection); return 0; }
Incloure el servidor MySQL en el programa C
Això és el que he utilitzat en l'aplicatiu presentaciosdl d'arthropoda, per fer una mena de presentació powerpoint d'insectes que accedeix directament a la base de dades.
creat per Joan Quintana Compte, juny 2011