Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6976607
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T17:31:06+00:00 2026-05-27T17:31:06+00:00

I am trying to connect c++ to mysql. I am using visual c++ 2008

  • 0

I am trying to connect c++ to mysql.
I am using visual c++ 2008 Express Edition.

//Write a c++ Program to add a user to mysql/
//The User Should be permitted to only “select” entries from the given database

#include<stdio.h>
#include<conio.h>
#include<windows.h>
#include<iostream>
#include <sql.h>
#include <sqlext.h>
#include <sqltypes.h> 

using namespace std;

//SQL_ACTIVE_CONNECTIONS
//sql::Connection             *_con;
//sql::mysql::MySQL_Driver    *_driver;
//_driver = sql::mysql::get_mysql_driver_instance();
//_con = _driver->connect("tcp://127.0.0.1:3306", "user", "password");


MYSQL *conn;
MYSQL *newconn;

char USERNAME[100];                 //MYSQL username
char PASSWORD[100];                 //MYSQL password

void CreateConnection(void);        //Create Connection with mysql server.
void SelectDatabase(void);          //Create and select database.
void CreateUser(void);              //Create New user and grant Permission.
void NewConn(void);                 //Create new connection with user information
void CreateTable(void);             //Create "Product" Table to operate.
void InsertData(void);              //insert data into product table. 
void DeleteData(void);              //Delete data from product table.
void SelectData(void);              //Retrieve data From product table;


int main()
{
    char ch;
    int select;
    char uname[100],pass[100];
    CreateConnection();
    SelectDatabase();
    cout<<"\n\nEnter your login infomation\nTo delete and retrieve use ADMIN account\n";
    cout<<"If you are new user your account will be create with insert privilege.\n";
    cout<<"UserName :";                                     
    gets(uname);
    mysql_escape_string(USERNAME,uname,strlen(uname));      //Assign username in USERNAME variable.
    cout<<"Password :";
    gets(pass);
    mysql_escape_string(PASSWORD,pass,strlen(pass));        //Assign password in PASSWORD variable
    CreateUser();
    NewConn();
    cout<<"\nSelect option.";
    do
    {
        cout<<"\n1. INSERT\n2. DELETE\n3. RETRIEVE\n";
        cin>>select;
        switch(select)
        {
        case 1:
            InsertData();
            break;
        case 2:
            DeleteData();
            break;
        case 3:
            SelectData();
            break;
        default:
            printf("Wrong selection \n");
            break;
        }
        cout<<"Do You want to continue.....(Y/N)\n";
    }while(('Y'==getchar())||('y'==getchar()));
    mysql_close(newconn);
    return 0;
}


//Create connection with mysql server with username and password NULL.
void CreateConnection()
{
    conn = mysql_init(NULL);
    if (conn == NULL)
    {
        cout<<"Error : %s\n"<<mysql_error(conn);
        exit(1);
    }
    if(mysql_real_connect(conn, "localhost", NULL,NULL, NULL, 0, NULL, 0) == NULL)
    {
        cout<<"Error : %s\n", mysql_error(conn);
        exit(1);
    }
}


//select the database, if it is not present then create .
void SelectDatabase()
{

    if(mysql_query(conn, "create database user"))   //Query for creat3 database USER
    {
        if(mysql_errno(conn)==1007)                 //Error number 1007 means database already Exist
        {
            if(mysql_select_db(conn,"user"))        //Query for Selecte database USER
            {
                cout<<"Error :",mysql_error(conn);
                exit(1);
            }
        }
        else
        {
            cout<<"Error :",mysql_error(conn);
            exit(1);
        }
    }
    else                                            //This else part will be executed only if database is create without error                                  
    {
        if(mysql_select_db(conn,"user"))            //Query for Selecte database USER
        {
            cout<<"Error :",mysql_error(conn);
            exit(1);
        }
        CreateTable();                              //creating tables in USER database
    }   
}

//Create account for new user and grant permission
void CreateUser()
{
    char cmd[200];  
        sprintf(cmd,"create user '%s'@'localhost' identified by '%s'",USERNAME,PASSWORD); //prepare query to create user with USERNAME and PASSWORD.
        if(mysql_query(conn,cmd))
        {
            if(mysql_errno(conn)==1396)     //Error number 1396 means that user already exists
            {
                cout<<"WELCOME %s\n"<<USERNAME;
            }
            else
            {
                cout<<mysql_error(conn);
                exit(1);
            }
        }
        else
        {       
            sprintf(cmd,"grant insert on user.* to '%s'@'localhost'",USERNAME); //grant permission for created user.
            if(mysql_query(conn,cmd))
            {
                cout<<mysql_error(conn);
                exit(1);
            }
            else
            {
                cout<<"Your Account created %S\n"<<USERNAME;
            }
        }
        mysql_close(conn);
}

//create sample table PRODUCT with two coloumn 1.P_ID and 2.P_Name
void CreateTable()
{
    if(mysql_query(conn,"CREATE TABLE product (P_Id INT(6) NOT NULL AUTO_INCREMENT,P_NAME VARCHAR(100) NOT NULL,PRIMARY KEY (P_Id));"))
    {
        cout<<"Error :%s"<<mysql_error(conn);
        exit(1);
    }
    else
    {
        cout<<"Table created\n";
    }
}

//create connection with USERNAME and PASSWORD supplied by user. 
void NewConn()
{

    newconn = mysql_init(NULL);

  if (newconn == NULL) {
      cout<<"Error : %s\n"<< mysql_error(newconn);
      exit(1);
  }

  if (mysql_real_connect(newconn, "localhost", USERNAME,PASSWORD,"user", 0, NULL, 0) == NULL) {
      cout<<"Error : %s\n"<< mysql_error(newconn);
      exit(1);
  }
}

//insert data into Product table.
void InsertData()
{

    char cmd[200];
    char pname[100],PNAME[100];
    cout<<"Enter Product Name :";  //product name that would be added in PRODUCT details
    cin>>pname;
    mysql_escape_string(PNAME,pname,strlen(pname));
    cout<<cmd<<"insert into Product (P_NAME) values('%s')"<<pname);

    if(mysql_query(newconn,cmd))
    {
        cout<<"Error :%s"<<mysql_error(newconn);
        exit(1);
    }
    else
    {
        cout<<"product added\n";
    }
}

//Delete data  from product table, it require ADMIN privilege.
void DeleteData()
{
    char cmd[200];
    char pname[100],PNAME[100];
    cout<<"Enter Product Name :";           //Enter product name to delete the details
    cout<<pname;
    mysql_escape_string(PNAME,pname,strlen(pname));
    sprintf(cmd,"delete from Product where P_Name='%s'",pname);//prepare delete query.
    if(mysql_query(newconn,cmd))
    {
        cout<<"Error :%s",mysql_error(newconn);
    }
    else
    {
        cout<<"product deleted\n";
    }
}

//Retrieve data from Product table, it require ADMIN privilege.
void SelectData()
{
    char cmd[200];
    char pname[100],PNAME[100];
    MYSQL_RES *result;
    MYSQL_ROW row;
    int num_fields,i;
    cout<<"Enter Product Name :"; //Enter product name to see the details
    cin>>pname;
    mysql_escape_string(PNAME,pname,strlen(pname));
    cout<<cmd<<"Select * from Product where P_Name='%s'"<<pname); //prepare select statement
    if(mysql_query(newconn,cmd))
    {
        cout<<"Error :%s"<<mysql_error(newconn);
    }
    else
    {
        result = mysql_store_result(conn);
        num_fields = mysql_num_fields(result);
        cout<<"\nPRODUCT ID\tPRODUCT NAME\n";
        cout<<"----------------------------------\n";
        while ((row = mysql_fetch_row(result)))
        {
            for(i = 0; i < num_fields; i++)
            {
                printf("%s\t\t ", row[i] ? row[i] : "NULL"); //display product information
            }
            printf("\n");
        }
        mysql_free_result(result);
    }
}

But the Compiler Is not able to link With MySql Project.

I think I need to Link throgh Project->properties something Libraries.
I had installed mysql-connector-c++-1.0.5-win32 from [http://dev.mysql.com/downloads/mirror.php?id=369369] website.

Still it is not able to detect my files.
Please help me.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T17:31:07+00:00Added an answer on May 27, 2026 at 5:31 pm

    http://dev.mysql.com/doc/refman/5.1/en/connector-cpp-apps-windows-visual-studio.html

    Please read the link and add the references properly. I suggest you read the documentation atleast once since you want to use it.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to connect a C# application (using Visual C# 2008 Express Edition) to
I am trying to connect to a remote MySQL database using Visual C# 2008
Hi am using MS visual VC++ 2008 trying to connect mysql though vc++ code..getting
I'm trying to connect to SQL Server 2008 express database from Visual Studio 2010
I'm trying to connect to a MySQL 5 database using the MySQL ODBC 5.1
I've been recently trying to connect to a hosted MySQL using Java but can't
I'm trying to connect to MySQL using MATLAB R2009b 64 bit and the mysql.cpp
I am trying to connect to a MySQL database using the mysql_connect() command however
I am trying to connect to MYSQL database using the Pear DB library. IS
I'm trying to connect to a MySQL database using my ASP.NET Web Forms Application.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.