C++ tutorial-retrieve and manipulate data with Mysql


C++ and Mysql database

 

C++ code to manipulate your database

Finally, you will write C or C++ code to connect and manipulate your data as shown below:

#include <iostream>

#include <windows.h>

#include <C:/Program Files/MySQL/MySQL Server 5.5/include/mysql.h>

using namespace std;

void displaydata(MYSQL* conn){

MYSQL_RES *result;

MYSQL_ROW row;

int num_fields;

int i;

//retrieve and display data

mysql_query(conn, "SELECT * FROM tblstudent");

result = mysql_store_result(conn);

num_fields = mysql_num_fields(result);

while ((row = mysql_fetch_row(result)))

{

for(i = 0; i < num_fields; i++)

{

cout<<row[i]<<"\t";

}

cout<<"\n";

}



mysql_free_result(result);//clear result set from memory

}

void insertdata(MYSQL* conn){



char *qstr;

qstr="INSERT INTO tblstudent VALUES('3','Chantha')";

mysql_query(conn,qstr);



}



void deletedata(MYSQL* conn){

char *id;

char *qstr;

qstr="DELETE FROM tblstudent WHERE id='3'";

mysql_query(conn,qstr);



}

int main()

{

MYSQL* conn;

//create connection

conn = mysql_init(NULL);

mysql_real_connect(conn, "localhost", "root","root","dbstudent",3306 , NULL, 0);

//display data using mysql_query() method

displaydata(conn);

//insert data using insert into statement

insertdata(conn);

//delete data using delete from statement

deletedata(conn);

//close connection

mysql_close(conn);


system("PAUSE");

return 0;

}

Output:

c++ myql output


Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.