数据封装就是使用类似结构体的形式,将多个相关数据合并到一个结构体中,在程序中作为一个整体进行付值和调用 *** 作。
*** 作封装就是对多个重复使用且具有相同功能的语句进行整合,打包成一个实现固定功能的函数。
1.需要用到mysql c api2.步骤通常是:连接数据库,执行查询,异常处理这些。
3.你需要对api 进行一些了解,然后合理调用。
参考代码:
//连接代码:
/*
* connect1.c - connect to and disconnect from MySQL server
*/
#include <my_global.h>
#include <my_sys.h>
#include <mysql.h>
static char *opt_host_name = NULL /* server host (default=localhost) */
static char *opt_user_name = NULL /* username (default=login name) */
static char *opt_password = NULL /* password (default=none) */
static unsigned int opt_port_num = 0 /* port number (use built-in value) */
static char *opt_socket_name = NULL /* socket name (use built-in value) */
static char *opt_db_name = NULL /* database name (default=none) */
static unsigned int opt_flags = 0 /* connection flags (none) */
static MYSQL *conn/* pointer to connection handler */
int
main (int argc, char *argv[])
{
/* initialize connection handler */
conn = mysql_init (NULL)
if (conn == NULL)
{
fprintf (stderr, "mysql_init() failed (probably out of memory)\n")
exit (1)
}
/* connect to server */
if (mysql_real_connect (conn, opt_host_name, opt_user_name, opt_password,
opt_db_name, opt_port_num, opt_socket_name, opt_flags) == NULL)
{
fprintf (stderr, "mysql_real_connect() failed\n")
mysql_close (conn)
exit (1)
}
/* disconnect from server */
mysql_close (conn)
exit (0)
}
//处理sql 语句的函数:
void
process_statement (MYSQL *conn, char *stmt_str)
{
MYSQL_RES *res_set
if (mysql_query (conn, stmt_str) != 0) /* the statement failed */
{
print_error (conn, "Could not execute statement")
return
}
/* the statement succeededdetermine whether it returned data */
res_set = mysql_store_result (conn)
if (res_set) /* a result set was returned */
{
/* process rows and then free the result set */
process_result_set (conn, res_set)
mysql_free_result (res_set)
}
else /* no result set was returned */
{
/*
* does the lack of a result set mean that the statement didn't
* return one, or that it should have but an error occurred?
*/
if (mysql_field_count (conn) == 0)
{
/*
* statement generated no result set (it was not a SELECT,
* SHOW, DESCRIBE, etc.)just report rows-affected value.
*/
391
Processing SQL Statements
printf ("%lu rows affected\n",
(unsigned long) mysql_affected_rows (conn))
}
else /* an error occurred */
{
print_error (conn, "Could not retrieve result set")
}
}
}
//以上提供的是常规的处理,你需要根据实际情况完善。
//同时调用了一些mysql 的api函数。
ref:
MySQL
(Fourth Edition)
Paul DuBois
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)