开发者

c program to add a user to mysql

开发者 https://www.devze.com 2023-03-25 08:53 出处:网络
I am going to add a user to MySQL through C program. I amgoing to do final year project in MySQL. Don\'t get me wrong i开发者_如何学JAVAf I ask wrong. I have one doubt in this concept, that is we can

I am going to add a user to MySQL through C program. I am going to do final year project in MySQL. Don't get me wrong i开发者_如何学JAVAf I ask wrong. I have one doubt in this concept, that is we can add a new user with some privilege as root. After that do we need a logout for root or not. If I do , how to logout root.

//header files inclusion

int main(void)
{
    //declared MYSQL,MYSQL_REs,MYSQL_ROW variables.

    // here declared username,pwd,localhost,databasename

    // here declared variable to query

    con = mysql_init(NULL);

    /* connection to database */
    if(!mysql_real_connect(con,server,username,password,database,0,NULL,0)) {
    {
        printf("error in connection\n");
        exit(1);
    }

    printf("\n Enter the username to create a user in DB\n");
    scanf("%s",name);

    printf("\n Enter password \n");
    scanf("%s",pwd);

    sprintf(sql_addUser,"create user '%s'@'localhost' identified by '%s';",name,pwd);
    mysql_query(con,sql_addUser);

    sprintf(sql_grantAcc,"grant INSERT on '%s'.* to '%s'@'localhost';",databse,name);
    mysql_query(con,sql_grantAcc);

So here we created a user in root mode. Then I need to enter MySQL using newly created user so that may I need to logout or close connection. Please give me a solution to how change the user mode.

I assumed to change the user mode we need to close the established connection is this right or not?

mysql_free_result(result);
    mysql_close(con);

con = mysql_init(NULL);
    if(!mysql_real_connect(con,server,name,pwd,database,0,NULL,0)) {
    {
        printf("error in connection\n");
        exit(1);
    }


If you wish to use mysql_real_connect() i believe it would be best to close the connection before attempting to reopen as a diferent user, as the API description for mysql_real_connect() doesnt describe how it handles such situation (might work but the process could be left open on the mysql server, pending a timeout).

You can however use the mysql_change_user() call of the API.

syntax:

my_bool mysql_change_user(MYSQL *mysql, const char *user, const char *password, const char *db)

More info in the respective api description here, it's implemented since MySQL 3.23.3.

0

精彩评论

暂无评论...
验证码 换一张
取 消