2.步骤通常是:连接数据库,执行查询,异常处理这些。
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)
}
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
假如用户输入的姓名和年龄值分别保存在变量name,age中:char sql_insert[200]
sprintf(sql_insert, "INSERT INTO table values('%s','%d')", name, age)
mysql_query(&mysql_conn, sql_insert)
上述语句在执行完sprintf语句后,sql_insert中保存的是INSERT查询语句字符串,sql_insert作为mysql_query()语句的参数即可实现正确的插入。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)