|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
请问大佬们,这个我想打印数据库信息该怎么改写呢
- #include <stdio.h>
- #include <mysql.h>
- #include <string>
- #include <iostream>
- using namespace std;
- const char* host = "127.0.0.1";
- const char* user = "root";
- const char* pw = "123456a";
- const char* database_name = "爬虫";
- const int port = 3306;
- typedef struct Student {
- int cid;
- string captioon;
- }Student;
- int main(){
- //初始化
- MYSQL* con = mysql_init(NULL);
- //设置编码
- mysql_options(con,MYSQL_SET_CHARSET_NAME, "GBK");
- //链接数据库
- if (!mysql_real_connect(con, host, user, pw, database_name, port, NULL, 0)) {
- fprintf(stderr, "%s", mysql_error(con));
- return -1;
- }
- //定义sql语句
- char sql[255];
- sprintf(sql, "select * from class");
- //执行sql语句
- if (!mysql_query(con, sql)) {
- fprintf(stderr, "%s", mysql_error(con));
- return -1;
- }
- MYSQL_RES* res = mysql_store_result(con);
- char tempStr[255];
- MYSQL_ROW row;
- while ((row = mysql_fetch_row(res))) {
- sprintf(tempStr, "%s", row[0]);
- printf(tempStr);
- }
- //关闭数据库
- mysql_close(con);
- return 0;
-
- }
复制代码
你好!你可以根据你的需求对代码进行一些修改,比如在打印行信息时,你可以将数据格式化为更易阅读的格式。以下是一个改进后的版本:
- #include <stdio.h>
- #include <mysql.h>
- #include <string>
- #include <iostream>
- using namespace std;
- const char* host = "127.0.0.1";
- const char* user = "root";
- const char* pw = "123456a";
- const char* database_name = "爬虫";
- const int port = 3306;
- typedef struct Student {
- int cid;
- string captioon;
- } Student;
- int main() {
- // 初始化
- MYSQL* con = mysql_init(NULL);
- // 设置编码
- mysql_options(con, MYSQL_SET_CHARSET_NAME, "utf8");
- // 链接数据库
- if (!mysql_real_connect(con, host, user, pw, database_name, port, NULL, 0)) {
- fprintf(stderr, "%s\n", mysql_error(con));
- return -1;
- }
- // 定义sql语句
- char sql[] = "SELECT * FROM class";
- // 执行sql语句
- if (mysql_query(con, sql)) {
- fprintf(stderr, "%s\n", mysql_error(con));
- return -1;
- }
- MYSQL_RES* res = mysql_store_result(con);
- MYSQL_ROW row;
- MYSQL_FIELD *field;
- unsigned int num_fields = mysql_num_fields(res);
- while ((field = mysql_fetch_field(res))) {
- cout << field->name << "\t";
- }
- cout << endl;
- while ((row = mysql_fetch_row(res))) {
- for (unsigned int i = 0; i < num_fields; ++i) {
- if (row[i]) {
- printf("%s\t", row[i]);
- } else {
- printf("NULL\t");
- }
- }
- printf("\n");
- }
- // 释放结果集
- mysql_free_result(res);
- // 关闭数据库
- mysql_close(con);
- return 0;
- }
复制代码
注意:在这个版本中,我修改了字符编码设置为UTF-8,因为UTF-8兼容性更好,可以支持更多字符集。你可以根据你的实际情况进行调整。此外,我还添加了字段名的打印,以便更清楚地显示输出的数据。
|
|