Search code examples
mysqlctimeformat-specifiers

Print C Format specifiers in a string independently


I have a field 'time' in my Mysql server and want to query to database to get this field in my C program as below:

select * from tbl where str_to_date(time, '%M %d %Y %H:%i:%s') > given_date

Now the problem is printing format specifiers in my query string. How to print %d, %i and %s in the query string?


Solution

  • If you want to use % in a formatting string, without using it as a format specifier, use %% instead:

    char buffer[1024] = {};
    
    char query_string[] = { 
          "select * from tbl where str_to_date(time, '%%M %%d %%Y %%H:%%i:%%s') > '%s'"
    };
    
    char given_date[] = { "03 4 2014 14:55:21" };
    
    sprintf(buffer, query_string, given_date);
    
    printf(buffer);
    

    Output:

    select * from tbl where str_to_date(time, '%M %d %Y %H:%i:%s') > '03 4 2014 14:55:21'