Insert System or current time into mysql table column

I have to send a count of number to mysql database table, with the current time. The current time must be inserted automatically when the count inserted. How to do it? In the below code, I tried to inserted the time by using the query. But it doesn't work at all.

And another problem is here the cout outputs can be written to a notepad by "freopen("out.txt","w",stdout)" line. But for the printf it doesn't work. How can I do it?

#include "stdafx.h"
#include <iostream>
#include <conio.h>
#include <string>
#include <fstream>
#include <windows.h>
#include <mysql.h>
#include <ctime>

using namespace std;

int main()
MYSQL* conn;

conn = mysql_init(NULL);
if (mysql_real_connect(conn,"","root","root","trafficdetails",0,NULL,0) !=0)
cout << "Succesfully Connected to MySQL database xxxx" << endl;

////if(mysql_query(conn, "select Count from Stored_Vehicle_Count"))
if(mysql_query(conn, "INSERT INTO Sample (Current_Time) VALUES (time(0))"))
fprintf(stderr, "%s\n", mysql_error(conn));
return -1;

////time_t now = time(0);
res = mysql_use_result(conn);

// output table name
printf("MySQL Tables in mysql database:\n");
while ((row = mysql_fetch_row(res)) != NULL)
////printf("%s %s %s %s\n", row[0], row[1], row[2], row[3]);
printf("%s %s %s %s\n", row[0], row[1], row[2], row[3]);
cout <<row[0]<< endl;
// FILE *fpIn;
// fpIn = fopen("char-array.txt", "wb");
// close connection

return 0;

You should use the built in SQL function.

Change your query to:

"INSERT INTO Sample (Current_Time) VALUES (Now())"

As for the printf, I haven't used it in ages but you could try to leave a space between the last specifier and the newline character.

printf("%s %s %s %s \n", row[0], row[1], row[2], row[3]);
Last edited on
Thanks man.

Both worked.
Topic archived. No new replies allowed.