C下使用mysql
Demonstrates how to use plain C to create a MySQL database, connect to it, create a table with fields, populate the table, execute an SQL query, and print the results. No MFC required - uses only plain C.
#include <conio.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include "winsock.h"
#include "mysql.h"
MYSQL *mysql = NULL;
void MySQLError(void)
{
fprintf(stderr, "%s\n", mysql_error(mysql));
exit(1);
}
void ExecuteSQL(char *fmt, ...)
{
char SQL[1000] = {0};
int retval;
va_list args;
va_start(args, fmt);
if (_vsnprintf(SQL, sizeof(SQL)-1, fmt, args) < 0)
{
fprintf(stderr, "SQL query truncated! Increase SQL buffer size in ExecuteSQL\n");
exit(1);
}
va_end(args);
retval = mysql_query(mysql, SQL);
if (retval)
{
fprintf(stderr, "Original SQL Statement: %s\n", SQL);
fprintf(stderr, "%s\n", mysql_error(mysql));
exit(2);
}
}
int main()
{
UINT i;
UINT FieldCount;
MYSQL_RES *res = NULL;
MYSQL_ROW row = NULL;
MYSQL_FIELD *field;
char *DBName = "Test";
char *TableName = "People";
char *CreateDB = "CREATE DATABASE IF NOT EXISTS %s";
char *DropTable = "DROP TABLE IF EXISTS %s";
char *CreateTable = "CREATE TABLE IF NOT EXISTS %s (\n"
"ID INT UNSIGNED AUTO_INCREMENT, \n"
"FirstName VARCHAR(32), \n"
"MiddleName VARCHAR(32), \n"
"LastName VARCHAR(32), \n"
"Address1 VARCHAR(50), \n"
"Address2 VARCHAR(50), \n"
"City VARCHAR(50), \n"
"State VARCHAR(2), \n"
"Zip VARCHAR(5), \n"
"Email VARCHAR(50), \n"
"Gender VARCHAR(1), \n"
"WorkPhone VARCHAR(50), \n"
"HomePhone VARCHAR(50), \n"
"CellPhone VARCHAR(50), \n"
"BirthDate DATE NULL, \n"
"Primary Key (ID) \n"
")\n";
char *AddRecord = "INSERT INTO %s (FirstName, LastName) VALUES ('FirstName %03d', 'LastName %03d')";
char *GetRecords = "SELECT ID, FirstName, LastName FROM %s";
// Initialize MySQL
mysql = mysql_init(NULL);
// Connect to MySQL
if (!(mysql_real_connect(mysql, "localhost", "admin", "", NULL, mysql->port, 0, 0)))
MySQLError();
// Create database
ExecuteSQL(CreateDB, DBName);
// Connect to temporary database
if (mysql_select_db(mysql, DBName))
MySQLError();
// Delete table if it already exists.
ExecuteSQL(DropTable, TableName);
// Create table
ExecuteSQL(CreateTable, TableName);
// Insert some data into the table.
for (i = 0; i < 200; i++)
ExecuteSQL(AddRecord, TableName, i, i);
// Execute query
ExecuteSQL(GetRecords, TableName);
// Store the recordset
if ((res = mysql_store_result(mysql)) == NULL)
MySQLError();
// Print the recordset
printf("Table %s\n", TableName);
while((field = mysql_fetch_field(res)) != NULL)
printf("%s\t", field->name);
printf("\n");
FieldCount = mysql_num_fields(res);
while((row = mysql_fetch_row(res)) != NULL)
{
for (i = 0; i < FieldCount; i++)
printf("%s\t", row[i]);
printf("\n");
}
printf("\nTotal rows: %d\n", mysql_num_rows(res));
// Free the recordset
mysql_free_result(res);
// Close the connection
mysql_close(mysql);
printf("\nPrint any key to continue...\n");
getche();
}
如果有问题,请加入mysql++.lib
在VC里的toos->option->directories中将include增加一个c:\mysql\include,将lib增加一个c:\mysql\lib,将libmysql.dll和libmysql.lib拷到当前目录下,并且把libmysql.lib增加到工程中。
2, 建立与服务器的连接。
Include <mysql.h> //包含头文件
MYSQL *conn;//定义一个MYSQL类型结构,这个几乎在所有的后面的编程中都需要
MYSQL *mysql_init(MYSQL *conn);//如果conn=NULL,返回一个新分配的句柄结构返回,反之则重新初始化该结构,出现错误则返回NULL;
MYSQL *mysql_real_connect(MYSQL * connection,const char *server_host,const char *sql_urs_name,const char *sql_password,const char *db_name,unsigned int port_number,const char *unix_socket_name,unsigned int flags);//连接MYSQL服务器,里面的参数应该很清楚了,一般port_number和unix_socket_name的值为0和NULL。例如:
mysql_real_connect(conn_ptr,"localhost","sagely","secret","ra",0,NULL,0);
void mysql_close(MYSQL *connection);关闭一个连接。
3, 执行SQL语句
mysql_select_db(MYSQL *connection,const char *db_name);选定某个数据库。
int mysql_query(MYSQL *connection,const char *query)//他将执行query语句,运行成功将返回0,例如mysql_query(conn_ptr, Create table cert_info(...),将创建一个名为cert_info的表,几乎所有的SQL语句都能这么执行。呵呵,是不是显得很简单,他就和命令行中输入的SQL语句差不多。在使用上面函数的时候一般会使用
my_ulonglong mysql_affected_rows(MYSQL *connection),这个函数返回的是mysql_query对进行改动的行的数量。
4, 处理检索到的数据
当我们可以执行SQL语句以后,那么就很容易执行增加删除修改等操作,但是假若检索出来的数据存储在哪里呢?
MYSQL_RES *mysql_use_result(MYSQL *connection)这个函数得到一个连接对象返回一个结果集合指针,出错时返回NULL。不过他只是返回一个集合对象初始化来接收数据,并没有将任何检索到的数据返回到结果集合中。
MYSQL_ROW mysql_fetch_row(MYSQL_RES *result)这个函数获得mysql_use_resul得到的结果结构体,并从中检索单个行,并返回分配给行结构体的数据,没有更多数据或出错时,返回NULL。
Unsigned int mysql_field_count(MYSQL *connection)它得到一个连接对象并返回在集合中字段的数目。
于是有上面的基础我们就可以理解下面这段了:(没有错误处理)
mysql_init(&conn_ptr);
mysql_real_connect(conn_ptr,"localhost","sagely","secret","ra",0,NULL,0);
mysql_query(conn_ptr,"SELECT * form usr_info);
res_ptr=mysql_use_result(&conn_ptr);
sqlrow=mysql_fetch_row(res_ptr);
for(int i=0;i<mysql_field_count(&conn_ptr);i++){printf("%s ",sqlrow);}
MYSQL_FIELD *mysql_fetch_field(MYSQL_RES *result)它返回的是列的信息,比如列的名称,列所在表名称等等,有了这个就可以将列标题与数据想对应起来了。