由于项目运用到数据库,就想着用C++来操作数据库。一开始准备用C++创建一个数据库的,但没找到方法。后来参考别人的博客,找到了向数据库中写数据的C++代码
#include<mysql.h>
#include<iostream>
#include<string>
#include<winsock.h>
#include<time.h>
#include<stdio.h>
using namespace std;
int main()
{
if (mysql_library_init(0, NULL, NULL))
{
printf("could not initialize MySQL library\n");
getchar();
exit(1);
}
MYSQL mydata;
mysql_init(&mydata);
MYSQL *ret = mysql_real_connect(&mydata, "127.0.0.1", "root", "123456", "test", 0, NULL, 0);
if (!ret)
{
printf("Failed to connect to database:%s\n", mysql_error(&mydata));
getchar();
exit(1);
}
int i;
while (cin >> i)
{
time_t t ;
struct tm current_time;
time(&t); //获取系统日期和时间
localtime_s(¤t_time, &t); //获取当地日期和时间
string str;
int year = 1900 + current_time.tm_year;
int month = 1 + current_time.tm_mon;
int day = 1 + current_time.tm_mday;
int hour = current_time.tm_hour;
int min = current_time.tm_min;
int sec = current_time.tm_sec;
int type = 1;
string pass_rate = "true";
double diatance_move = 1.0 / i;
str = "insert into weldingworkpiece VALUES (";
str += to_string(year);
str += ",";
str += to_string(month);
str += ",";
str += to_string(day);
str += ",";
str += to_string(hour);
str += ",";
str += to_string(min);
str += ",";
str += to_string(sec);
str += ",'D:\\/吉纳尔\\/";
str += to_string(year);
str += "_";
str += to_string(month);
str += "_";
str += to_string(day);
str += "_";
str += to_string(hour);
str += "_";
str += to_string(min);
str += "_";
str += to_string(sec);
str += ".bmp',";
str += "";
str += to_string(type); //型号
str += ",";
str += to_string(1); //是否合格
str += ",";
str += to_string(diatance_move); //偏移量
str += ");";
//cout << str.c_str() << endl;
//const char* strl= str.c_str();
int ret1 = mysql_query(&mydata, str.c_str());
if (ret1 != 0)
{
printf("error:%s\n", mysql_error(&mydata));
getchar();
system("pause");
}
}
MYSQL_RES *results;
MYSQL_ROW record;
mysql_query(&mydata, "SELECT * FROM weldingworkpiece");
results = mysql_store_result(&mydata);
//if (results == NULL) cout << "asd" << endl;
int record_num;
record_num = mysql_num_rows(results);
cout << record_num << endl;
while ((record = mysql_fetch_row(results)) != NULL) {
printf("%s - %s \n", record[0], record[6]);
}
mysql_close(&mydata);
mysql_server_end();
system("pause");
return 0;
}