Подключение Visual C ++ 2008 к MySql - PullRequest
0 голосов
/ 28 декабря 2011

Я пытаюсь подключить c ++ к mysql.Я использую Visual C ++ 2008 Express Edition.

// Написание программы на C ++ для добавления пользователя в mysql / // Пользователю должно быть разрешено только «выбирать» записи из данной базы данных

#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);
    }
}

Но компилятор не может связываться с проектом MySql.

Я думаю, что мне нужно связать через Project-> свойства что-то с библиотеками.Я установил mysql-connector-c ++ - 1.0.5-win32 с [http://dev.mysql.com/downloads/mirror.php?id=369369] веб-сайта.

Тем не менее он не может обнаружить мои файлы.Пожалуйста, помогите мне.

1 Ответ

0 голосов
/ 28 декабря 2011

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

Пожалуйста, прочитайте ссылку и добавьте ссылки правильно.Я предлагаю вам хотя бы раз прочитать документацию, поскольку вы хотите ее использовать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...