Mysql database api introduction and explanation

<div class="iteye-blog-content-contain" style="font-size: 14px"><p><div id="Article"> </p>
<p> <p>链接的流程图</p> </p>
<p> <p><img alt="这里写图片描述" src="/uploadfile/Collfiles/20171118/2017111809063750.png" /></p> </p>
<p> <h3>一,API介绍</h3> </p>
<p> <h4>1,初始化函数</h4> </p>
<p> <p>MYSQL *<a href="https://www.2cto.com/database/MySQL/" target="_blank" class="keylink">mysql</a>_init(MYSQL *mysql)</p> </p> <p> <p>return Assigned handle MYSQL* pointer </p> </p>
<p> <p>mysql can pass NULL</p> </p>

<p> <h4 id="2连接到mysql&lt;a href=" https:="" www.2cto.com="" atabase="" target="_blank" class="keylink">数据库&quot;&gt;2,连接到my<a href="https://www.2cto.com/database/" target="_blank" class="keylink">sql数据库</a></h4> </p>
<p> <p>MYSQL *mysql_real_connect(MYSQL *mysql, const char *host, const char *user, const char *passwd, const char *db, unsigned int port, const char *unix_socket, unsigned long client_flag)</p> </p>
<p> <p>参数介绍</p> mysql 初始化的句柄指针 host 主机地址 user 用户名 –The password of the mysql database root passwd user db The database port port to be connected is generally filled with 0, the default port of mysql is 3306 unix_socket local socket, generally filled in NULL client_flag The connection flag is generally filled with 0 </p>
<p> <p> ;<strong>Return value: </strong> The connection handle is returned on success, and NULL on failure</p> </p>
<p> <h4 id="3 Set the character set for login - after login">3, Set the character set for login – After login </h4> </p>
<p>  <blockquote> </p>
<p>  <p>int mysql_set_character_set(MYSQL *mysql, char *csname)</p> </p>
<p> < /blockquote> </p>
<p> <p> Parameters: </p> mysql connection handle csname character set name utf8 </p>
<p> <h4 id=" 4The function of query is very powerful - you can add, delete, modify and check">4, the query function is very powerful, you can add, delete, modify and search</h4> </p>
<p> <blockquote> </p>
<p>  <p> int mysql_query(MYSQL *mysql, const char *query)</p> </p>
<p> </blockquote> </p>
<p> <p>参数介绍:</p> mysql 连接句柄 query 执行的sql </p>
<p> <p>返回值:</p> </p>
<p> <pre class="brush:sql;"></p>
<p>Success returns 0</p>
<p>Failure returns non-0</p>
<p></pre> ; </p>
<p> <h4 id="5 function to get result set">5, function to get result set</h4> </p>
<p>  <blockquote> </p>
<p>  <p>MYSQL_RES *mysql_store_result(MYSQL *mysql)</p> </p>
<p> </blockquote>  </p>
<p> <p>Return value: If reading the result set fails, mysql_store_result() also returns a Null pointer. You can check for errors by checking if mysql_error() returns a non-empty string, mysql_errno() returns a non-zero value, or mysql_field_count() returns 0. </p> </p>












<p> <blockquote> </p>
<p>  <p>MYSQL_FIELD *mysql_fetch_field(MYSQL_RES *result)</p> </p>
<p> < /blockquote> </p>
<p> <p>Description</p> </p>
<p> <p> Returns the columns of the result set in the MYSQL_FIELD structure. Call this function repeatedly to retrieve information about all columns in the result set. When no fields remain, mysql_fetch_field() returns NULL. </p> </p>
<p> <p> Every time a new SELECT query is executed, mysql_fetch_field() is reset to return information about the first field. Calls to mysql_field_seek() also affect the fields returned by mysql_fetch_field(). </p> </p>
<p> <p> If mysql_query() is called to perform a SELECT on a table, but mysql_store_result() is not called, if mysql_fetch_field() is called to request the length of a BLOB field, MySQL will return the default blob length (8KB). 8KB was chosen because MySQL does not know the maximum length of a BLOB. Should be made configurable at a later date. Once the result set has been retrieved, field-&gt;max_length will contain the length of the maximum value for that column in the particular query. </p> </p>









<p> <p> The lengths of field values ​​in a row can be obtained by calling mysql_fetch_lengths(). For empty fields and fields containing NULL, the length is 0. By examining pointers to field values, they can be distinguished. If the pointer is NULL, the field is NULL, otherwise the field is empty. </p> </p>
<p> <p>Return value</p> </p>
<p> <p>The MYSQL_ROW structure of the next row. Returns NULL if there are no more rows to retrieve or an error occurred. </p> </p>
<p> <h4 id="10show number of rows affected">10,show number of rows affected</h4> </p >
<p> <blockquote> </p>
<p>  <p>my_ulonglong mysql_affected_rows(MYSQL *mysql)</p> </p>
<p> < /blockquote> </p>
<p> <
p>Description</p> </p> <p> <p>Returns the number of rows changed by the last UPDATE, the number of rows deleted by the last DELETE, or the number of rows inserted by the last INSERT statement. For UPDATE, DELETE or INSERT statements, it can be called immediately after mysql_query(). For SELECT statements, mysql_affected_rows() works similarly to mysql_num_rows(). </p> </p>
<p> <p>Return value</p> </p>
<p> <p>An integer greater than 0 indicates the number of rows affected or retrieved. "0" means that the UPDATE statement did not update the record, there were no rows matching WHERE in the query, or the query was not executed. "-1" means that the query returned an error, or, for a SELECT query, mysql_affected_rows() was called before mysql_store_result() was called. Since mysql_affected_rows() returns an unsigned value, check if it is "-1" by comparing the return value with "(my_ulonglong)-1" or the equivalent "(my_ulonglong)~0". </p> </p>
<p> <pre class="brush:sql;"></p>
<p>#include </p>
<p>  < stdio.h></p>
<p>   </p>
<p>#include </p>
<p>   <



<p>     <mysql.h></p>
<p>       #include </p>
<p>      <unistd.h></p>
<p>        #define _USER_ &quot;root&quot; //用户名 #define _HOST_ &quot;127.0.0.1&quot; //host #define _PASSWD_ &quot;123&quot; //root 用户名密码 #define _DB_ &quot;scott&quot; //库名 #define _PORT_ 3306 //port //打印信息 结果集 void show_information(MYSQL_RES * res, MYSQL *mysql) { int i; MYSQL_ROW row; // //unsigned long *lengths; unsigned int num_fields; MYSQL_FIELD *field; //字段名 // 数据的长度unsigned int mysql_num_fields(MYSQL_RES *result) num_fields = mysql_num_fields(res); //返回列长unsigned long *mysql_fetch_lengths(MYSQL_RES *result) //lengths = mysql_fetch_lengths(res); printf(&quot;num_fields = [%d]\n&quot;, num_fields); //字段名 for (i = 0; i &lt; num_fields, field = mysql_fetch_field(res); i++) { printf(&quot; %s\t&quot;, field-&gt;name); } printf(&quot;\n&quot;); printf(&quot;--------------------------------------------------------------\n&quot;); while ((row = mysql_fetch_row(res))) { for (i = 0; i &lt; num_fields; i++) { printf(&quot;%s \t&quot;, row[i] ? row[i] : NULL); } printf(&quot;\n&quot;); } //释放结果集 mysql_free_result(res); printf(&quot;--------------------------------------------------------------\n&quot;); //显示受影响的行数 printf(&quot; %ld rows in set\n&quot;, (long) mysql_affected_rows(mysql)); } int main(int argc, char *argv[]) { int ret, i; MYSQL *mysql; MYSQL_RES * res; char strsql[512] = { 0}; //1,mysql_init 初始化 mysql = mysql_init(NULL); if (mysql == NULL) { printf(&quot;mysql_init error\n&quot;); return -1;} //2,mysql_real_connect链接 mysql = mysql_real_connect(mysql, _HOST_, _USER_, _PASSWD_, _DB_, 0, NULL, 0); if (mysql == NULL) { printf(&quot;mysql_real_connect error\n&quot;); return -1; } printf(&quot;connect mysql ok\n&quot;); //处理字符问题的函数 if ( mysql_set_character_set(mysql, &quot;utf8&quot;) != 0) { printf(&quot; mysql_set_character_set error\n&quot;); mysql_close(mysql); exit(1); } //===========================输入sql语句====================== while (1) { memset(strsql, 0x00, sizeof(strsql)); write(STDOUT_FILENO, &quot;yoursql&gt;&quot;,amp;quot;); //处理字符问题的函数 if ( mysql_set_character_set(mysql, &quot;utf8&quot;) != 0) { printf(&quot; mysql_set_character_set error\n&quot;); mysql_close(mysql); exit(1); } //===========================输入sql语句====================== while (1) { memset(strsql, 0x00, sizeof(strsql)); write(STDOUT_FILENO, &quot;yoursql&gt;&quot;,amp;quot;); //处理字符问题的函数 if ( mysql_set_character_set(mysql, &quot;utf8&quot;) != 0) { printf(&quot; mysql_set_character_set error\n&quot;); mysql_close(mysql); exit(1); } //===========================输入sql语句====================== while (1) { memset(strsql, 0x00, sizeof(strsql)); write(STDOUT_FILENO, &quot;yoursql&gt;&quot;, ; //Read the sql string input by the client read(STDIN_FILENO, strsql, sizeof(strsql)); //Exit processing if (strncasecmp(strsql, &quot;quit&quot;, 4) == 0) { printf(&quot;client exit processing\n&quot;); break; } //Enter sql's ret = mysql_query(mysql, strsql); if (ret) { printf(&quot;mysql_query error\n&quot ;); continue; } res = mysql_store_result(mysql); //processing with result set if (res != NULL) { show_information(res, mysql); } else { //display the number of rows affected printf(& quot; Query OK, %ld row affected\n&quot;,(long) mysql_affected_rows(mysql)); } } // char sqlstr[] = &quot;select *from emp&quot;; // //Query Statement int mysql_query(MYSQL *mysql, const char *query) // ret = mysql_query(mysql, sqlstr); // if (ret) { // printf(&quot;mysql_query error\n&quot;); // return -1;// } // // //查询的结果集MYSQL_RES *mysql_store_result(MYSQL *mysql) // res = mysql_store_result(mysql); //MYSQL_ROW mysql_fetch_row(MYSQL_RES *result) // if ( res != NULL) { // show_information(res); // // 数据的长度unsigned int mysql_num_fields(MYSQL_RES *result) // num_fields = mysql_num_fields(res); // //返回列长unsigned long *mysql_fetch_lengths(MYSQL_RES *result) // //lengths = mysql_fetch_lengths(res); // printf(&quot;num_fields = [%d]\n&quot;, num_fields); // //字段名 // for (i = 0; i &lt; num_fields, field = mysql_fetch_field(res); i++) { // printf(&quot; %s\t&quot;, field-&gt;name); // } // printf(&quot;\n&quot;); // while (row = mysql_fetch_row(res)) { // // for (i = 0; i &lt; num_fields; i++) { // printf(&quot;%s \t&quot;, row[i]); // } // printf(&quot;\n&quot;); // } // //Free the result set // mysql_free_result(res); // } //Close mysql mysql_close(mysql); return 0; } </p>
<p>      </unistd.h></p>
<p>     </mysql.h></p>
<p>    </ string.h></p>
<p>   </stdlib.h></p>
<p>  </stdio.h></pre> </p>
< p> <p><img alt="Write picture description here" src="/uploadfile/Collfiles/20171118/2017111809064163.gif" /></p> </p>
<p>  <h3 id="Second SQL preprocessing-prevent injection and increase efficiency">Second, SQL preprocessing prevents injection and increases efficiency</h3> </p>
<p> <h4 id="1insert preprocessing">1,insert preprocessing< /h4> </p>
<p> <p>流程图</p> </p>
<p> <p><img alt="这里写图片描述" src="/uploadfile/Collfiles/20171118/2017111809064167.png" /></p> </p>









<p> <p>Return value</p> </p>
<p> <p> On success, return a pointer to the MYSQL_STMT structure. Returns NULL if memory overflows. </p> </p>
<p> <h6 id="2 insert prepared statement"> 2, insert prepared statement </h6> </p>
<p>  <blockquote> </p>
<p>  <p>int mysql_stmt_prepare(MYSQL_STMT *stmt, const char *query, unsigned long length)</p> </p>
<p > </blockquote> </p>
<p> <p>Description</p> </p>
<p> <p> Given mysql_stmt_init() returns The statement handle, prepares the SQL statement pointed to by the string query, and returns the status value. String length should be defined by & ldquo;length" parameter is given. String must contain 1 SQL statement. Statements should not be terminated by semicolons (‘;’) or \g.
</p> </p> <p> <p> By embedding the question mark character “?” parameter marker. </p> </p>
The <p> <p> tag is only legal in a specific position in an SQL statement. For example, it can be in the VALUES() list of an INSERT statement (to specify column values ​​for rows), or in the comparison part of a column in a WHERE clause (to specify comparison values). However, for IDs (such as table or column names), they are not allowed, and operands to specify binary operators (such as the equal sign “=”) are not allowed. The latter restriction is necessary because the parameter type cannot be determined. In general, parameters are only legal in DML (Data Manipulation Language) statements, not in DDL (Data Definition Language) statements. </p> </p>
<p> <p> Before executing the statement, you must use mysql_stmt_bind_param() to bind parameter markers to application variables. </p> </p>
<p> <p>Return value</p> </p>
<p> <p> Returns 0 if the statement was successfully processed . If an error occurs, a non-zero value is returned. </p> </p>
<p> <h6 id="3 get parameter"> 3, get parameter </h6> </p>
<p> < blockquote> </p>



<p> <p> Returns the number of parameter markers in the prepared statement. </p> </p>
<p> <p>Return value</p> </p>
<p> <p>Unsigned representing the number of parameters in the statement long integer. </p> </p>
<p> <h6 id="4 parameter binding"> 4, parameter binding </h6> </p>
<p>  <blockquote> </p>
<p>  <p>my_bool mysql_stmt_bind_param(MYSQL_STMT *stmt, MYSQL_BIND *bind)</p> </p>
<p> < /blockquote> </p>
<p> <p>Description</p> </p>
<p> <p> mysql_stmt_bind_param() is used to bind data for parameter markers in SQL statements to pass to mysql_stmt_prepare(). It uses the MYSQL_BIND structure to provide data. "bind" is the address of an array of the MYSQL_BIND structure. As expected by the client library, the array contains 1 element for each "?" parameter marker that appears in the query.
</p> </p> <p> <p>Suppose you prepared the following statement: </p> </p>








<p> <p>If the statement is an UPDATE, DELETE, or INSERT, the total number of rows changed, deleted, or inserted can be found by calling mysql_stmt_affected_rows(). If this is a statement such as SELECT that produces a result set, mysql_stmt_fetch() must be called to fetch the data before calling any other function that causes the query to be processed. For more information on how to fetch results, see Section 25.2.7.11, "mysql_stmt_fetch()". </p> </p>
<p> <p> For a statement that generates a result set, before executing the statement, you can request mysql_stmt_execute() to open the cursor for the statement by calling mysql_stmt_attr_set(). If a statement is executed multiple times, mysql_stmt_execute() will close any open cursors before opening new ones. </p> </p>
<p> <p>Return value</p> </p>
<p> <p> Returns 0 if the execution is successful. If an error occurs, a non-zero value is returned. </p> </p>
<p> <h6 id="6 returns the number of preprocessed lines"> 6, returns the number of preprocessed lines</h6> </p >
<p>&

<p> </blockquote> </p>
<p> <p>Description</p> </p>
<p> <p>Return to last execution The total number of rows changed, deleted, or inserted by the statement. For UPDATE, DELETE, or INSERT statements, they can be called immediately after mysql_stmt_execute(). For SELECT statements, mysql_stmt_affected_rows() works like mysql_num_rows(). </p> </p>
<p> <p>Return value</p> </p>
<p> <p>An integer greater than 0 indicates affected or the number of rows retrieved. For an UPDATE statement, "0" means that no records have been updated, that there are no rows in the query that match the WHERE clause, or that no query has been executed. "-1" indicates that an error was returned, or that mysql_stmt_affected_rows() was called before calling mysql_stmt_store_result() for a SELECT query. Since mysql_stmt_affected_rows() returns an unsigned value, you can check the ”


<p>#include </p>
<p>  <stdio.h></p>
<p>   </p>
<p>#include &quot;mysql.h&quot;</p>
<p>#include </p>
<p>   <stdlib.h></p>
<p>     #include </p>
<p>    <string.h></p>
<p>      #define _HOST_ &quot;localhost&quot; //主机 #define _USER_ &quot;root&quot; //mysql用户,非主机 #define _PASSWD_ &quot;123&quot; //密码 #define _DBNAME_ &quot;scott&quot; //库名 #define STRING_SIZE 50 #define DROP_SAMPLE_TABLE &quot;DROP TABLE IF EXISTS test_table&quot; // if EXISTS 好处 是如果表不存在,执行不会报错 #define CREATE_SAMPLE_TABLE &quot;CREATE TABLE test_table(col1 INT,\ col2 VARCHAR(40),\ col3 SMALLINT,\ col4 TIMESTAMP)&quot; #define INSERT_SAMPLE &quot;INSERT INTO test_table(col1,col2,col3) VALUES(?,?,?)&quot; void prepare_insert(MYSQL *mysql); int main() { //1.初始化 MYSQL * mysql = NULL; mysql = mysql_init(NULL) ; if(mysql == NULL ) { printf(&quot;mysql init err\n&quot;); exit(1); } //2.connect mysql = mysql_real_connect(mysql, _HOST_,_USER_, _PASSWD_,_DBNAME_, 0, NULL,0); if(mysql == NULL) { printf(&quot;mysql_real_connect connect err\n&quot;); exit(1) ; } printf(&quot;welcome to mysql \n&quot;); prepare_insert(mysql); //3. close mysql_close(mysql); return 0; } void prepare_insert(MYSQL *mysql) { MYSQL_STMT *stmt;/ /Preprocessed handle -- identifies the only preprocessed sql in the process MYSQL_BIND bind[3];//Bind variable my_ulonglong affected_rows; int param_count; short small_data; int int_data; char str_data[STRING_SIZE]; unsigned long str_length; my_bool is_null; if (mysql_query(mysql, DROP_SAMPLE_TABLE))//delete table { fprintf(stderr, &quot; DROP TABLE failed\n&quot;); fprintf(stderr, &quot; %s\n&quot; , mysql_error(mysql)); exit(0); } if (mysql_query(mysql, CREATE_SAMPLE_TABLE))//create table { fprintf(stderr, &quot;CREATE TABLE failed\n&quot;); fprintf(stderr, &quot; %s\n&quot;, mysql_error(mysql)); exit(0); } /* Prepare an INSERT query with 3 parameters */ /* (the TIMESTAMP column is not named; the server */ /* sets it to the current date and time) */ stmt = mysql_stmt_init(mysql); //预处理的初始化 if (!stmt) { fprintf(stderr, &quot; mysql_stmt_init(), out of memory\n&quot;); exit(0); } if (mysql_stmt_prepare(stmt, INSERT_SAMPLE, strlen(INSERT_SAMPLE))) //insert 语句 的预处理 { fprintf(stderr, &quot; mysql_stmt_prepare(), INSERT failed\n&quot;); fprintf(stderr, &quot; %s\n&quot;, mysql_stmt_error(stmt)); exit(0); } fprintf(stdout, &quot; prepare, INSERT successful\n&quot;); /* Get the parameter count from the statement */ param_count= mysql_stmt_param_count(stmt);//获得参数个数 fprintf(stdout, &quot; total parameters in INSERT: %d\n&quot;, param_count); if (param_count != 3) /* validate parameter count */ { fprintf(stderr, &quot; invalid parameter count returned by MySQL\n&quot;); exit(0); } /* Bind the data for all 3 parameters */ memset(bind, 0, sizeof(bind)); /* INTEGER PARAM */ /* This is a number type, so there is no need to specify buffer_length */ bind[0].buffer_type= MYSQL_TYPE_LONG;//对应int类型 bind[0].buffer= (char *)&amp;int_data;//内存地址的映射 bind[0].is_null= 0; bind[0].length= 0; /* STRING PARAM */ bind[1].buffer_type= MYSQL_TYPE_STRING; bind[1].buffer= (char *)str_data;//char 100 bind[1].buffer_length= STRING_SIZE; bind[1].is_null= 0; bind[1].length= &amp;str_length; /* SMALLINT PARAM */ bind[2].buffer_type= MYSQL_TYPE_SHORT; bind[2].buffer= (char *)&amp;small_data; bind[2].is_null= &amp;is_null;//The indicator of whether it is null bind[2].length= 0; /* Bind the buffers */ if (mysql_stmt_bind_param(stmt, bind)) //Bind variable parameter binding { fprintf(stderr, &quot; mysql_stmt_bind_param() failed\n&quot;); fprintf(stderr, &quot; %s\n&quot;, mysql_stmt_error(stmt)); exit(0); } //The first wave of assignment int_data= 10; /* integer */ strncpy(str_data, &quot;MySQL&quot;, STRING_SIZE); /* string */ str_length= strlen(str_data); / /INSERT INTO test_table(col1,col2,col3) VALUES(10,'MySQL',null) /* INSERT SMALLINT data as NULL */ is_null= 1;//Indicates whether the inserted third field is null //insert into test_table(col1,col2,col3) values(10,'MySQL',null); /* Execute the INSERT statement - 1*/ if (mysql_stmt_execute(stmt)) //Preprocessing execution, the first execution { fprintf( stderr, &quot; mysql_stmt_execute(), 1 failed\n&quot;);fprintf(stderr, &quot; %s\n&quot;, mysql_stmt_error(stmt)); exit(0); } /* Get the total number of affected rows */ affected_rows= mysql_stmt_affected_rows(stmt);//预处理的影响条数 fprintf(stdout, &quot; total affected rows(insert 1): %lu\n&quot;, (unsigned long) affected_rows); if (affected_rows != 1) /* validate affected rows */ { fprintf(stderr, &quot; invalid affected rows by MySQL\n&quot;); exit(0); } //第二波赋值 int_data= 1000; strncpy(str_data, &quot;The most popular Open Source database&quot;, STRING_SIZE); str_length= strlen(str_data); small_data= 1000; /* smallint */ is_null= 1; /* reset */ //INSERT INTO test_table(col1,col2,col3) VALUES(1000,'The most popular Open Source database',1000) //insert into test_table(col1,col2,col3) values(1000,'The most popular Open Source database',1000); /* Execute the INSERT statement - 2*/ if (mysql_stmt_execute(stmt))//第二次执行 { fprintf(stderr, &quot; mysql_stmt_execute, 2 failed\n&quot;); fprintf(stderr, &quot; %s\n&quot;, mysql_stmt_error(stmt)); exit(0); } /* Get the total rows affected */ affected_rows= mysql_stmt_affected_rows(stmt); fprintf(stdout, &quot; total affected rows(insert 2): %lu\n&quot;, (unsigned long) affected_rows); if (affected_rows != 1) /* validate affected rows */ { fprintf(stderr, &quot; invalid affected rows by MySQL\n&quot;); exit(0); } /* Close the statement */ if (mysql_stmt_close(stmt)) { fprintf(stderr, &quot; failed while closing the statement\n&quot;); fprintf(stderr, &quot; %s\n&quot;, mysql_stmt_error(stmt)); exit(0);} } </p>
<p>    </string.h></p>
<p>   </stdlib.h></p>
<p>  </stdio.h></pre> </p>
<p> <h4 id="2-查询预处理">2, 查询预处理</h4> </p>
<p> <p>流程图<br /> <img alt="这里写图片描述" src="/uploadfile/Collfiles/20171118/20171118090651118.png" /></p> </p>
<p> <h5 id="api介绍">api介绍</h5> </p>
<p> <blockquote> </p>
<p>  <p>MYSQL_RES *mysql_stmt_param_metadata(MYSQL_STMT *stmt)</p> </p>
<p> </blockquote> </p>
<p> <p>提前指定结果集的操作</p> </p>
<p> <pre class="brush:sql;"></p>
<p>//select *from dept; 查询语句的使用</p>
<p>#include </p>
<p>  <stdio.h></p>
<p>   </p>
<p>#include </p>
<p>   <stdlib.h></p>
<p>     #include </p>
<p>    <string.h></p>
<p>      #include </p>
<p>     <mysql.h></p>
<p>       #define _USER_ &quot;root&quot; //用户名 #define _HOST_ &quot;127.0.0.1&quot; //host #define _PASSWD_ &quot;123&quot; //root 用户名密码 #define _DB_ &quot;scott&quot; //库名 #define _PORT_ 3306 //port //============================stmt ====================================== #define STRING_SIZE 50 //mysql 查询语句 #define SELECT_SAMPLE &quot;SELECT deptno, dname, loc FROM dept&quot; void seach_information(MYSQL *mysql){ int i, count = 0;; MYSQL_STMT *stmt; // MYSQL_BIND bind[3]; //条件变量 MYSQL_RES *prepare_meta_result; //结果集 unsigned long length[3]; int param_count, column_count, row_count; int int_data; //序号 char str_name[STRING_SIZE]; //姓名 char str_loc[STRING_SIZE]; my_bool is_null[3]; //参数的控制 my_ulonglong row_unm;//===========================init start========================= //初始化sql预处理语句 stmt = mysql_stmt_init(mysql); if (!stmt) { fprintf(stderr, &quot; mysql_stmt_init(), out of memory\n&quot;); exit(0); } //绑定参数my_bool mysql_stmt_bind_param(MYSQL_STMT *stmt, MYSQL_BIND *bind) //mysql_stmt_bind_param(stmt, bind); if (mysql_stmt_prepare(stmt, SELECT_SAMPLE, strlen(SELECT_SAMPLE))) { fprintf(stderr, &quot; mysql_stmt_prepare(), SELECT failed\n&quot;); fprintf(stderr, &quot; %s\n&quot;, mysql_stmt_error(stmt)); exit(0); } fprintf(stdout, &quot; prepare, SELECT successful\n&quot;); fprintf(stdout, &quot; total parameters in SELECT: %d\n&quot;, param_count); param_count = mysql_stmt_param_count(stmt); if (param_count != 0) /* validate parameter count */ { fprintf(stderr, &quot; invalid parameter count returned by MySQL\n&quot;); exit(0); } prepare_meta_result = mysql_stmt_result_metadata(stmt); if (!prepare_meta_result) { fprintf(stderr, &quot; mysql_stmt_result_metadata(), returned no meta information\n&quot;); fprintf(stderr, &quot; %s\n&quot;, mysql_stmt_error(stmt)); exit(0); } column_count= mysql_num_fields(prepare_meta_result); fprintf(stdout, &quot; total columns in SELECT statement: %d\n&quot;, column_count); if (column_count != 3) /* validate column count */ { fprintf(stderr, &quot; invalid column count returned by MySQL\n&quot;); exit(0); } //mysql_stmt_execute(stmt); //发送占位符到mysql数据库上???? if (mysql_stmt_execute(stmt)) { fprintf(stderr, &quot; mysql_stmt_execute(), failed\n&quot;); fprintf(stderr, &quot;%s\n&quot;, mysql_stmt_error(stmt)); exit(0); } //初始化参数 memset(bind, 0, sizeof(bind)); /* INTEGER COLUMN */ bind[0].buffer_type= MYSQL_TYPE_LONG; bind[0].buffer= (char *)&amp;int_data; bind[0].is_null= &amp;is_null[0]; bind[0].length= &amp;length[0]; //varchar -- MYSQL_TYPE_VAR_STRING /* name COLUMN */ bind[1].buffer_type= MYSQL_TYPE_VAR_STRING; bind[1].buffer= (char *)str_name; bind[1].buffer_length = STRING_SIZE; bind[1].is_null = &amp;is_null[1]; bind[1].length = &amp;length[1]; /* loc COLUMN */ bind[2].buffer_type= MYSQL_TYPE_VAR_STRING; bind[2].buffer= (char *)&amp;str_loc; bind[2].buffer_length = STRING_SIZE; bind[2].is_null = &amp;is_null[2]; bind[2].length = &amp;length[2]; //绑定数据 mysql_stmt_bind_result(stmt, bind); mysql_stmt_store_result(stmt);// //init row row_count= 0; //查询的结果 row_unm = mysql_stmt_num_rows(stmt); //打印数据 //mysql_stmt_fetch(stmt); //mysql_stmt_fetch(stmt); printf(&quot;row_unm = %ld\n&quot;, row_unm); for (i = 0; i &lt; row_unm; i++) { mysql_stmt_fetch(stmt); row_count++; fprintf(stdout, &quot; row %d\n&quot;, row_count); /* column 1 */ fprintf(stdout, &quot; column1 (integer) : &quot;); if (is_null[0]) fprintf(stdout, &quot; NULL\n&quot;); else fprintf(stdout, &quot; %d(%ld)\n&quot;, int_data, length[0]); /* column 2 */ fprintf(stdout, &quot; column2 (string) : &quot;); if (is_null[1]) fprintf(stdout, &quot; NULL\n&quot;); else fprintf(stdout, &quot; %s(%ld)\n&quot;, str_name, length[1]); /* column 3 */ fprintf(stdout, &quot;column3 (string) : &quot;); if (is_null[2]) fprintf(stdout, &quot; NULL\n&quot;); else fprintf(stdout, &quot; %s(%ld)\n&quot;, str_loc, length[2]); fprintf(stdout, &quot;\n&quot;); //break; } //释放内存 /* Validate rows fetched */ if (row_count != 10) { fprintf(stderr, &quot; MySQL failed to return all rows\n&quot;); exit(0); } /* Free the prepared result metadata */ mysql_free_result(prepare_meta_result); /* Close the statement */ mysql_stmt_close(stmt); } //===================================================================== int main(int argc, char *argv[]) { int ret, i; MYSQL *mysql; MYSQL_RES * res; MYSQL_ROW row; // //unsigned long *lengths; unsigned int num_fields; MYSQL_FIELD *field; //字段名 //1,mysql_init 初始化 mysql = mysql_init(NULL); if (mysql == NULL) { printf(&quot;mysql_init error\n&quot;); return -1; } //2,mysql_real_connect链接 mysql = mysql_real_connect(mysql, _HOST_, _USER_, _PASSWD_, _DB_, 0, NULL, 0); if (mysql == NULL) { printf(&quot;mysql_real_connect error\n&quot;); return -1; } printf(&quot;connect mysql ok\n&quot;); //设置一下字符编码utf8 if (mysql_set_character_set(mysql, &quot;utf8&quot;)) { printf(&quot; mysql_set_character_set error\n&quot;); return -1; } seach_information(mysql); // char sqlstr[] = &quot;select *from emp&quot;; // //查询语句int mysql_query(MYSQL *mysql, const char *query) // ret = mysql_query(mysql, sqlstr); // if (ret) { // printf(&quot;mysql_query error\n&quot;); // return -1; // } // // //查询的结果集MYSQL_RES *mysql_store_result(MYSQL *mysql) // res = mysql_store_result(mysql);// // //MYSQL_ROW mysql_fetch_row(MYSQL_RES *result) // if ( res != NULL) { // // 数据的长度unsigned int mysql_num_fields(MYSQL_RES *result) // num_fields = mysql_num_fields(res); // //返回列长unsigned long *mysql_fetch_lengths(MYSQL_RES *result) // //lengths = mysql_fetch_lengths(res); // printf(&quot;num_fields = [%d]\n&quot;, num_fields); // //字段名 // for (i = 0; i &lt; num_fields, field = mysql_fetch_field(res); i++) { // printf(&quot; %s\t&quot;, field-&gt;name); // } // printf(&quot;\n&quot;); // while (row = mysql_fetch_row(res)) { // // for (i = 0; i &lt; num_fields; i++) { // printf(&quot;%s \t&quot;, row[i]); // } // printf(&quot;\n&quot;); // } // //释放结果集 // mysql_free_result(res); // } //关闭mysql mysql_close(mysql); return 0; } </p>
<p>     </mysql.h></p>
<p>    </string.h></p>
<p>   </stdlib.h></p>
<p>  </stdio.h></pre> </p>
<p> <p><img alt="这里写图片描述" src="/uploadfile/Collfiles/20171118/20171118090653119.gif" /></p> </p>
<p> <h3 id="事物的介绍">事物的介绍</h3> </p>
<p> <pre class="brush:sql;"></p>
<p>//mysql中的事务</p>
<p>#include </p>
<p>  <stdio.h></p>
<p>   </p>
<p>#include </p>
<p>   <stdlib.h></p>
<p>     #include </p>
<p>    <string.h></p>
mysql_error(mysql)); exit(0); } ret = mysql_OperationTran(mysql); //Open the transaction and modify the transaction attributes to manual commit if (ret != 0) { printf(&quot;mysql_OperationTran() err: %d\n&quot;, ret); return ret; } ret = mysql_query(mysql, sql01); //Insert the first row of data into the table ‘AAA’ if (ret != 0) { printf(& quot;mysql_query() err:%d\n&quot;, ret); return ret; } ret = mysql_query(mysql, sql02); //Insert the second row of data into the table‘BBB’ if (ret != 0) { printf(&quot;mysql_query() err:%d\n&quot;, ret); return ret; } ret = mysql_Commit(mysql); //manually commit the transaction if (ret != 0) { printf (&quot;mysql_Commit() err:%d\n&quot;, ret); return ret; } //////////AAA BBB is in. #if 1 ret = mysql_AutoTran(mysql); // = again = modify the transaction attribute to [automatic] commit if (ret != 0) { printf(&quot;mysql_OperationTran() err:%d\n&quot;, ret); return ret; } #else ret = mysql_OperationTran(mysql); // = again = modify the transaction attribute to [manual] commit if (ret != 0) { printf(&quot;mysql_OperationTran() err:%d\n&quot;, ret); return ret; } #endif ret = mysql_query(mysql, sql03); //Insert the third row of data into the table ‘CCC’ if (ret != 0) { printf(&quot;mysql_query() err :%d\n&quot;, ret); return ret; } ret = mysql_query(mysql, sql04); //Insert the fourth row of data into the table ‘DDD’ if (ret != 0) { printf(& ;quot;mysql_query() err:%d\n&quot;, ret); return ret; } ret = mysql_Rollback(mysql); //Direct rollback operation if (ret != 0) { printf(&quot;mysql_Rollback () err:%d\n&quot;, ret); return ret; } //Whether the rollback operation can roll back the values ​​of CCC and DDD depends on the transaction attributes. mysql_close(mysql); return 0; } </p> mysql_OperationTran() err:%d\n&quot;, ret); return ret; } #endif ret = mysql_query(mysql, sql03); //Insert the third row of data into the table ‘CCC’ if (ret != 0) { printf(&quot;mysql_query() err:%d\n&quot;, ret); return ret; } ret = mysql_query(mysql, sql04); //Insert the fourth row of data into the table‘ DDD’ if (ret != 0) { printf(&quot;mysql_query() err:%d\n&quot;, ret); return ret; } ret = mysql_Rollback(mysql); //Direct rollback operation if ( ret != 0) { printf(&quot;mysql_Rollback() err:%d\n&quot;, ret); return ret; } //Whether the rollback operation can roll back the values ​​of CCC and DDD depends on the transaction Attributes. mysql_close(mysql); return 0; } </p> mysql_OperationTran() err:%d\n&quot;, ret); return ret; } #endif ret = mysql_query(mysql, sql03); //Insert the third row of data into the table ‘CCC’ if (ret != 0) { printf(&quot;mysql_query() err:%d\n&quot;, ret); return ret; } ret = mysql_query(mysql, sql04); //Insert the fourth row of data into the table‘ DDD’ if (ret != 0) { printf(&quot;mysql_query() err:%d\n&quot;, ret); return ret; } ret = mysql_Rollback(mysql); //Direct rollback operation if ( ret != 0) { printf(&quot;mysql_Rollback() err:%d\n&quot;, ret); return ret; } //Whether the rollback operation can roll back the values ​​of CCC and DDD depends on the transaction Attributes. mysql_close(mysql); return 0; } </p> } ret = mysql_query(mysql, sql04); //Insert the fourth row of data into the table ‘DDD’ if (ret != 0) { printf(&quot;mysql_query() err:%d\n&quot; , ret); return ret; } ret = mysql_Rollback(mysql); //Direct rollback operation if (ret != 0) { printf(&quot;mysql_Rollback() err:%d\n&quot;, ret); return ret; } //Whether the rollback operation can roll back the values ​​of CCC and DDD depends on the transaction attributes. mysql_close(mysql); return 0; } </p> } ret = mysql_query(mysql, sql04); //Insert the fourth row of data into the table ‘DDD’ if (ret != 0) { printf(&quot;mysql_query() err:%d\n&quot; , ret); return ret; } ret = mysql_Rollback(mysql); //Direct rollback operation if (ret != 0) { printf(&quot;mysql_Rollback() err:%d\n&quot;, ret); return ret; } //Whether the rollback operation can roll back the values ​​of CCC and DDD depends on the transaction attributes. mysql_close(mysql); return 0; } </p>
<p>    </string.h></p>
<p>   </stdlib.h></p>
<p>  </stdio.h></pre> </p>
<p></div></p></div>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326400651&siteId=291194637