mysql -u root -p
CREATE DATABASE student;
USE student;
CREATE TABLE stu_info(
id INT NOT NULL PRIMARY KEY,
name VARCHAR(20) NOT NULL,
gender ENUM('M','F') NOT NULL,
age INT NOT NULL,
department ENUM('M','F') NOT NULL,
major VARCHAR(20) NOT NULL,
class VARCHAR(10) NOT NULL,
status ENUM('Y','N') DEFAULT 'Y'
);
insert into stu_info values(2013000, 'zhao guohui', 'M', 20, 'Department of CS', 'CS', 'JX1301', 'Y');
insert into stu_info values(2013002, 'li yang', 'M', 19, 'Department of Manager', 'Business Management', 'GS1303', 'Y');
gcc -Wall student_query.c -o student_query -lmysqlclient
CREATE DATABASE student;
USE student;
CREATE TABLE stu_info(
id INT NOT NULL PRIMARY KEY,
name VARCHAR(20) NOT NULL,
gender ENUM('M','F') NOT NULL,
age INT NOT NULL,
department ENUM('M','F') NOT NULL,
major VARCHAR(20) NOT NULL,
class VARCHAR(10) NOT NULL,
status ENUM('Y','N') DEFAULT 'Y'
);
insert into stu_info values(2013000, 'zhao guohui', 'M', 20, 'Department of CS', 'CS', 'JX1301', 'Y');
insert into stu_info values(2013002, 'li yang', 'M', 19, 'Department of Manager', 'Business Management', 'GS1303', 'Y');
编辑代码
//student_query.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql/mysql.h>
#define HOST "localhost"
#define USERNAME "root"
#define PASSWORD "houyong"
#define DATABASE "student"
int main(int argc, char const *argv[])
{
int field_num, field_count;
MYSQL mysql;
MYSQL_RES *res;
MYSQL_ROW row;
char query[50];
int i = 0;
mysql_init(&mysql); /* initialize the handler */
/* connect the local mysql database. */
if (mysql_real_connect(&mysql, HOST, USERNAME, PASSWORD, DATABASE, 0, NULL, 0) == NULL)
{
printf("Mysql connect error! %d: %s\n", mysql_errno(&mysql), mysql_error(&mysql));
exit(1);
}
printf("Mysql connect success, connection id: %d\n", mysql.thread_id);
while(1)
{
i ++;
printf("Please input SQL query(%d):", i);
gets(query);
/* use mysql_real_query() to query the table */
if (mysql_real_query(&mysql, query, strlen(query))!=0)
{
printf("Query table stu_info error! %d:%s\n", mysql_errno(&mysql), mysql_error(&mysql));
exit(1);
}
/* use mysql_use_result() to initialize the result sets */
if ((res = mysql_use_result(&mysql)) == NULL)
{
printf("Mysql use result error! %d: %s\n", mysql_errno(&mysql), mysql_error(&mysql));
exit(1);
}
/* use mysql_field_count() to return the column number */
for (field_count = 0; field_count <= mysql_field_count(&mysql); field_count ++)
{
if ((row = mysql_fetch_row(res)) == NULL)
{
break;
}
for(field_num = 0; field_num <= mysql_num_fields(&mysql); field_num ++)
{
printf("%s ", row[field_num]);
}
printf("\n");
}
mysql_free_result(res);
printf("Mysql query success!\n");
}
mysql_close(&mysql);
return 0;
}
gcc -Wall student_query.c -o student_query -lmysqlclient
./student_query
输入查询命令,如:select * from stu_info;