C ++ and C # simple sample code for accessing MySQL

Source: Internet
Author: User

Paste the sample code. It is very suitable for beginners. 1) C # access mysqlusing System; using System. collections. generic; using System. text; using MySql. data. mySqlClient; using System. data; using System. data. common; namespace SybaseUtilTest {class Program {// http://bugs.mysql.com/47422, interested friends, you can see how this bug is going static void testDataAdapter () {try {MySqlClientFactory factory = MySqlClientFactory. instance; DbConnection conn = factory. createConnection (); conn. C OnnectionString = string. format ("server = {0}; user id = {1}; password = {2}; database = {3}; port = {4}; pooling = false ", "localhost", "root", "passwd", "test", 3306); conn. open (); DbDataAdapter da = factory. createDataAdapter (); da. selectCommand = conn. createCommand (); da. selectCommand. commandText = "select * from t12345"; da. deleteCommand = conn. createCommand (); da. deleteCommand. commandText = "delete from t 12345 where id = @ id "; DbParameter param = factory. createParameter (); param. parameterName = "@ id"; param. dbType = DbType. int32; param. sourceColumn = "id"; param. sourceVersion = DataRowVersion. current; da. deleteCommand. parameters. add (param); da. deleteCommand. updatedRowSource = UpdateRowSource. none; DataTable dt = new DataTable ("t12345"); da. fill (dt); int index = 0; foreach (DataRow o in dt. rows) {If (o ["id"]. equals (4) {Console. writeLine (String. format ("index = {0}, to delete id = 4, col2 = {1}", index, o ["col2"]); break ;} index ++;} dt. rows [index]. delete (); da. update (dt); dt. acceptChanges (); da. dispose (); conn. close ();} catch (Exception ex) {Console. writeLine (ex. source + "" + ex. message + "" + ex. stackTrace) ;}} static void Main (string [] args) {testDataAdapter () ;}} 2) C ++ access (Directly call C-API) # include <iostream> # include <windows. h> # include <mysql. h ># include <string> static const char host [32] = "localhost"; static const char user [32] = "test "; static const char passwd [32] = "passwd"; static const char db [32] = "test";/** mysql> select * from t; + ---- + | id | + ---- + | 1 | + ---- + 1 row in set (0.00 sec) mysql> delimiter // mysql> create procedure get_t (in t1 int) -> begin-> Select id from t where id = t1;-> end-> // Query OK, 0 rows affected (0.05 sec) mysql> call get_t (1 ); -> // + ---- + | id | + ---- + | 1 | + ---- + 1 row in set (0.00 sec) Query OK, 0 rows affected (0.00 sec) */void test_more_results (MYSQL * h) {char str [512] = "insert into test_num values (101); insert into test_num values (122); commit ;"; int r = mysql_real_query (h, str, strlen (str); if (r) {const ch Ar * error = mysql_error (h); std: cout <"*** Connection Error" <error <std: endl ;} do {MYSQL_RES * res = mysql_store_result (h); mysql_free_result (res);} while (0 = mysql_next_result (h);} void test_proc_stmt (MYSQL * h) {MYSQL * mysql _ = h; MYSQL_BIND bind; MYSQL_BIND obind [1]; // test_more_results (mysql _); MYSQL_STMT * hStmt = ignore (mysql _); my_bool true_value = 1; mysql_stmt_a Ttr_set (hStmt, STMT_ATTR_UPDATE_MAX_LENGTH, (void *) & true_value); char SQL [] = "call get_t (?) "; // Char SQL [] =" select id from t where id =? "; If (mysql_stmt_prepare (hStmt, SQL, strlen (SQL) {std: cout <__line __< <": stmt prepare error: "<(mysql_stmt_error (hStmt) <std: endl; mysql_stmt_reset (hStmt); if (mysql_stmt_prepare (hStmt, SQL, strlen (SQL) {std :: cout <__line __< <": stmt prepare error:" <(mysql_stmt_error (hStmt) <std: endl; mysql_close (mysql _); exit (-1) ;}} int id = 1; unsigned long id_len = 0; memset (& bind, 0, sizeof (B Ind); bind. buffer_type = FIELD_TYPE_LONG; bind. buffer = (void *) & id; bind. is_unsigned = true; bind. length = & id_len; // bind [0]. buffer_length = sizeof (id); // bind [0]. is_null = 0; if (mysql_stmt_bind_param (hStmt, (MYSQL_BIND *) (& bind ))! = 0) {std: cout <__line __< <": stmt prepare error:" <(mysql_stmt_error (hStmt) <std: endl; mysql_close (mysql _); exit (-1);} if (mysql_stmt_execute (hStmt )! = 0) {std: cout <__line __< <": stmt prepare error:" <(mysql_stmt_error (hStmt) <std: endl; mysql_close (mysql _); exit (-1);} int t2; memset (obind, 0, sizeof (obind); obind [0]. buffer_type = MYSQL_TYPE_LONG; obind [0]. buffer = (char *) & t2; obind [0]. buffer_length = sizeof (t2); if (mysql_stmt_bind_result (hStmt, (MYSQL_BIND *) & obind [0])! = 0) {std: cout <__line __< <": stmt prepare error:" <(mysql_stmt_error (hStmt) <std: endl; mysql_close (mysql _); exit (-1);} if (mysql_stmt_store_result (hStmt )! = 0) {std: cout <__line __< <": stmt prepare error:" <(mysql_stmt_error (hStmt) <std: endl; mysql_close (mysql _); exit (-1);} int rows = mysql_stmt_num_rows (hStmt); for (int I = 0; I <rows; I ++) {if (mysql_stmt_fetch (hStmt) = 0) {std: cout <"id =" <t2 <std: endl ;}} mysql_stmt_free_result (hStmt ); mysql_stmt_close (hStmt);} // Just for demo only. // int main () {MYSQL * mysql _ = NULL; MYSQL_RES * result _ = NULL; MYSQL_ROW row _; mysql _ = mysql_init (mysql _); // if (mysql_real_connect (mysql _, host, user, passwd, db, 3306, NULL, CLIENT_MULTI_STATEMENTS) = NULL) if (mysql_real_connect (mysql _, host, user, passwd, db, 3306, NULL, CLIENT_MULTI_STATEMENTS) = NULL) {const char * error = mysql_error (mysql _); std :: cout <"*** Connection Error" <error <std: endl; return-1;} mysql_autocommit (mysql _, false); std :: string encodeStr = "set names 'gbk'"; mysql_real_query (mysql _, encodeStr. c_str (), encodeStr. size ();/* const char * tmpTableName = "t"; // assume you are querying the table 't'char str [512]; int cnt = 0; sprintf (str, "select count (*) as cnt from % s", tmpTableName); mysql_real_query (mysql _, str, strlen (str )); result _ = mysql_store_result (mysql _); while (row _ = mysql_fetch_row (result _) {// get the field value if (row _ [0]) {std :: cout <"count =" <row _ [0] <std: endl; // convert it into int cnt = atoi (row _ [0]); std:: cout <"cnt value =" <row _ [0] <std: endl ;}} mysql_free_result (result _); test_more_results (); */test_proc_stmt (mysql _); do {MYSQL_RES * res = mysql_store_result (mysql _); mysql_free_result (res);} while (0 = mysql_next_result (mysql _))); test_proc_stmt (mysql _); mysql_close (mysql _); return 0 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.