MySQL C ++ operation class

xiaoxiao2021-03-05  25

// contain three main classes / * 1. K_database database 2. k_record single record 3. K_Recordset record collection 3. K_field field information

K_Mysql.h

* / # include "mysql.h" #include using namespace std;

Class k_sqlfactory {public: k_sqlfactory () {clean ();} vector name_list; vector value_list;

String Where; String Tablename;

Void clean () {name_list.clear (); value_list.clear (); where = ""; tablename = "";

/ * Main features: Insert a new record return value: 0 Success-1 Execution Query Failed Description: Since the information provided by M_Value M_Field generates SQL statement and query * / void add_value (String newname, string newvalue) {name_list.push_back (newname) ; Value_list.push_back (newvalue);}; string get_add () {

IF ((Tablename.c_STR () == "") | (this-> Tablename.empty ()))) "-1"; string sqltext = "insert INTO"; SQLText = Tablename; SQLText = "("; INT j = (int) this-> name_list.size (); for (int i = 0; i

SQLText = Name_List [i]; if (i

J = (int) value_list.size (); for (i = 0; i

IF (i

} SQLText = ")"; return sqltext;} string get_edit () {ix ((TableName.c_STR () == "" || (this-> TableName.empty ()) || (this-> where.c_str () == "") || (this-> WHERE.EMPTY ()) Return "-1"; string sqltext = "update"; sqltext = Tablename; SQLText = "set"; int J = (int) THIS -> name_list.size (); for (int i = 0; i

} / * Main function: Edit-forming record return value: 0 Success-1 Execution Query Failed Description: Remove the Condition of M_where to generate the SQL statement and query * / string get_del () {string SqlText;

IF ((TableName.c_STR () == "") || (this-> Tablename.empty ()) || (this-> where.c_str () == "") || (this-> where.empty ()) RETURN "-1"; else {sqltext = "delete from"; sqltext = Tablename; sqltext = "where"; sqltext = where; return sqltext;}

} / * Main function: Return binary data to unhanective SQL text failure: "- 11" Main: Files below 1m * / String K_SreamRead (String FileName, mysql * mydata) {charf [1024 * 300 ]; // Basic buffer CHAR SQL [1024 * 300 * 2]; // SQL buffer not actual size 2 INT fleg; // file length INT Realleng; file * fp; fp = fopen (filename.c_str () , "RB"); if (fp == null) Return "--1"; fseek (fp, 0, seek_ek_end); fleng = ftell (fp);

FSeek (FP, 0, Seek_set); Realleng = (int) FREAD (BUF, SIZEOF (CHAR), FLENG, FP); mysql_real_escape_string (MyData, SQL, BUF, Realleng); Fclose (fp); string temp; Temp = SQL Return Temp;};}; ///

/ * 1 field operation 2 * ////

Class k_field {public: // Property Vector m_name; // field name vector m_type; // field type

Public: // Method BOOL ISNUM (INT NUM) // Is it a digital {IF (IS_NUM (M_Type [NUM])) Return True; Else Return False;}; Bool IsNum (String Num) // Is Digital {IF ( IS_NUM (M_Type [getfield_no (num))) Return True; Else Return false;}; // -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------- ---------------------------- BOOL Isdate (int Num) // is the date {if (m_type [num] == Field_Type_Date || m_type [NUM] == Field_Type_Datetime) Return True; Else Return False;}; Bool Isdate (String Num) // is Date {Int Temp; Temp = this-> getfield_no (NUM);

IF (m_type [temp] == field_type_date || m_type [temp] == field_type_datetime) Return True; else returnaf false;}; // ------------------------------------------------------------------------------------------------------------------------------------------------------------ -------------------------------------------------- ------------------------------------- BOOL Ischar (int Num) // is a character {ix (m_type [NUM] == Field_Type_String || M_Type [Num] == Field_Type_var_String || m_type [NUM] == Field_Type_Char) Return True; Else Return False;

}; Bool ischar (string num) // is a character {int Temp; Temp = this-> getfield_no (num); if (m_type [Temp] == Field_Type_String || M_Type [Temp] == Field_Type_var_string || m_type [TEMP ] == Field_Type_Char) Return True; Else Return False;}; // -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------- ---------------------- BOOL Isblob (int Num) // is binary data {if (is_blob (m_type [num])) Return True; Else Return false;}; bool isblob (string num) // is binary data {IF (is_blob (m_type [getfield_no))) Return True; else returnaf false;}; // -------- -------------------------------------------------- ------------------------------------------------ INT Getfield_no (String Field_name) // Get the serial number {for (unsigned int i = 0; i

}

///

/ * 1 Single Record 2 [INT] Operation [""] Operation * //// Class K_Record {public: // Property Vector M_RS; / / Result Set K_Field * m_field; // Field Information Size 4 words The memory of the record is that the number of records is very large, and the performance problem !!!!!!!!!!!!!!!!!!! Public: // method

Void K_Record (k_field * m_f) {m_field = m_f;}; void setdata (string value) {m_rs.push_back (value)

String Operator [] // [""] Operation {RETURN M_RS [M_Field-> getfield_no (s)];}; string operator [}} {return m_rs [num];}; bool isnull INT NUM // NULL value judge {if (M_RS [NUM] .c_str () == "") Return True; Else Return False;

}; Bool Isnull (String S) {IF (m_rs [m_field-> getfield_no (s)]. C_str () == "" "Return True; else returnaf false;}; // --------- -------------------------------------------------- ------------------- / * Main - Function: Return the result in the form of Value Tab Value * / std :: string getTabText () {string Temp; for (unsigned int i = 0; i

/ * 1 Record Set 2 [INT] Operation ["] Operation 3 Table Structure Operation 4 Data Insert Modification * ////

Class K_RecordSet {public: // Property Vector m_s; // Record Set INT M_RECORDCOUNT; // Record number INT m_field_num; // Field number k_field m_field; // field information // --------- ------------------------------------------- //

Mysql_res * fd; mysql_row rot; mysql * mydata; // ------------------------------- -------------------- // public: // method k_recordset () {};

INT getRecordCount () {return m_recordcount;}; // Get record number int getfieldnum () {return m_field_num;}; // Get field number k_field * getfield () {return & m_field;}; // Return Field // --- -------------------------------------------------- ---------------------- //

/ / -------------------------------------------------------------------------------------------- ----------------------------------------

/ * Main function: return the result set parameter: no. Record serial number

* / K_record operator [] (int NUM) // Return to the product number record {Return this-> m_s [Num];}; // ------------------- -------------------------------------------------- --------------------

/ / -------------------------------------------------------------------------------------------- ------------------------------------------};

///

/ * 1 Responsible for the connection of the database 2 Execute SQL statement (not returned) 3 Processing transaction * //// Class K_Database {

PUBLIC: K_DATABASE () {};

Public: // Property mysql * mydata; // msyql connection handle

Public: // method

/ / -------------------------------------------------------------------------------------------- ----------------------- / * Main features: Connection Database Parameter Description: 1 Host host IP address or when host name 2 user name 3 Passwd password 4 DB Database Name 5 Port Port Number 6 UINX Embedded Section 7 Client_Flag Customer Connection Parameters Return Value: 0 Success-1 Failure * / Int Connect (String Host, String User, String Passwd, String DB, Unsigned Int Port, unsigned Long Client_flag) {IF ((MyData = mysql_init) && mysql_real_connect (mydata, host.c_str (), user.c_str (), passwd.c_str (), db.c_str (), port, null , client_flag) {if (MySQL_SELECT_DB (MyData, DB.C_STR ()) <0) // Selecting the established database failed {mysql_close (myData); return -1;}} else {mysql_close (myData); // Initialization MySQL Structure failure return -1;} return 0; // success}; // --------------------------------- ----------------------------------- / * Main features: Close Database connection * / void disconnect () {Mysql_close (mydata);}; // ---------------------------------------- ----------------------------- / * Main function: Perform a non-return result query parameter: 1 SQL to be executed Query statement return value ; N to successfully expressed the number of rows-1 that is affected

* / Int execQuery (String SQL) {if (! Mysql_real_query (mydata, sql.c_str (), (unsigned long) sql.length ())) {return (int) mysql_affected_rows (mydata); // Get affected rows Number} else {return -1;} // failed

}; // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------- / * Main features: Test if the mysql server survives return value: 0 Represents successful -1 failed * / int ping () {if (! Mysql_ping (mydata)) Return 0; Else Return -1;}; // ------------------ -------------------------------------------------- --- / * Main function: Turn off the mysql server return value; 0 Success-1 failed * / int shutdown () {if (! Mysql_shutdown (mydata)) Return 0; else return -1;}; // -------- -------------------------------------------------- ----------------- / * Main function: Restart the MySQL server return value; 0 means successful -1 indicates failed * / int RE () {if (! Mysql_reload (myData) Return 0; else return -1;}; // ------------------------------------- ---------------------------------- // Description: Transaction support INNODB OR BDB Table Type // --- -------------------------------------------------- ----------------- / * Main function: Start transaction return value: 0 Successfully -1 indicates failed * / int start_transaction () {if (! Mysql_real_query (mydata, " START Transaction, ("Start Transaction")))))) {RETURN 0;} else {return -1;} // Execute Query Failed} // ------------- ------------------------- --------------------------------- / * Main function: Submit a return value: 0 Successfully-1 means failure * / Int commission () {

IF (! mysql_real_query (unsigned long) Strlen ("commit")))) {return 0;} else {return -1;} // execution query failed} // ------- -------------------------------------------------- ----------------- / * Main function: Roll Roll Transaction Return Value: 0 Successfully-1 Representation Failed * / int Rollback () {

IF (! mysql_real_query (unsigned long) Strlen ("rollback"))) RETURN 0; Else {return -1;} // execution query failed}; // -------- -------------------------------------------------- ---------------- / * Main function: get customer information * / string get_client_info () {return mysql_get_client_info ();}; // ---------- -------------------------------------------------- -------------- / * Main Features: Get customer version information * /// int GET_CLIENT_VERSION () {return mysql_get_client_version ();}; // --------- -------------------------------------------------- --------------- / * Main function: get host information * / string get_host_info () {return mysql_get_host_info (mydata);}; // ---------- -------------------------------------------------- -------------- / * Main features: Get server information * / string get_server_info () {return () @get_server_info (mydata);}; // ----------- -------------------------------------------------- ------------- / * Main features: Get server version information * /// int GET_SERVER_VERSION () {return mysql_get_server_version (mydata);}; // --------- -------------------------------------------------- - -------------- / * Main Features: Get the default character set of current connections * / string get_character_set_name () {return mysql_character_set_name (mydata);}; // ------- -------------------------------------------------- ------------------ // Main function return single value query string execquerygetsingvalue (String SQL) {mysql_res * res; mysql_row rot;

IF (! mysql_real_query (unsigned long) sql.length ())) {res = mysql_store_result (mydata); // Save Query Row = mysql_fetch_row (res); RETURN ((Row [0) ] == NULL) || (! Strlen)))? "- 1": row [0]; mysql_free_result (res);} else {return "--1";} // Execute Query Failure}; // --------------------------------------------- --------------------------------------- // Get the system time string getsystime () {Return ExecQuerygetsingValue ("Select now ()");}; // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------/*The main function: Establish a new database parameter: Name returns to the name of the new database: 0 Success-1 failed * / int create_db (string name) {string Temp; Temp = "Create Database"; Temp = Name; if (! Mysql_real_query (myData, Temp. C_STR (), (unsigned long) Temp.Length ())) Return 0; Else {return -1;} // Execute Query failed}; // ---------------------------------------------------------------------------------- -------------------------------------------------- -------- / * Main features: Delete the developed database parameters: Name To remove the name of the database returns: 0 Success-1 failed * / int Drop_db (string name) {String Temp; temp = " Drop Database "; temp = name; if (! Mysql_real_query (adata, temp.c_str (), (unsigned long) temp.length ())) Return 0; Else {return -1;} // Execute Query failed

}; Int execquerygetRecord (String SQL, K_Recordset & Record) {INT I, J; if (! MySQL_Real_Query (MyData, Sql.c_STR (), (Unsigned long) SQL.Length ()) // Execute Query {record.res = MySQL_Store_Result (myData); // Save Query Results

i = (int) mysql_num_rows (record.res); // Get recording quantity runt.m_recordcount = i; // Save record number j = mysql_num_fields (Record.res); // Get field number RECORD.M_FIELD_NUM = J; // Save the number of fields for (int x = 0; record.fd = mysql_fetch_field (record.res); x ) {record.m_field.m_name.push_back (record.fd-> name); record.m_field.m_type .push_back (Record. FD-> TYPE);} // .... while (Record.Row = mysql_fetch_row (record.res)) {k_record temp; for (int K = 0; k

}

}

//

// debug_corp.cpp: Define the entry point of the console application. //

#include "k_mysql.h"

INT Main (int Argc, char * argv []) {// ----------------------------------- ------------------------------------- K_Database a; int i; // ----- -------------------------------------------------- ------------

Printf ("Do the first test - Database connection - / N"); i = a.connect ("LocalHost", "root", "" "," kkk ", 3306, 0); if (i! = 0) {Printf ("Database Connection Failed / N"); return 0;} else {printf ("Successful connection to a developed database / N");} k_recordset sa; a.execQuerygetRecord ("SELECT * FROM FGDF" , SA); for (i = 0; i

K_SQLFActory SS; ss.tablename = "fgdf"; ss.where = "1"; ss.add_value ("gf", "fsdffffs"); ss.add_value ("GDF", "2004-4-5"); Printf ("% s", ss.get_add () .c_str ()); Printf ("/ n% s", ss.get_edit () .c_str ()); a.execquery (ss.get_add ()); a. ExecQuery (ss.get_edit ()); // ------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------

A.Disconnect (); // ------------------------------------------ ---------------------------------

Return 0;}

转载请注明原文地址:https://www.9cbs.com/read-32033.html

New Post(0)