显示标签为“Database”的博文。显示所有博文
显示标签为“Database”的博文。显示所有博文

2012年3月4日星期日

c++和c#访问mysql的简单代码示例


贴一份示例代码。
1) C#访问mysql
using 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
        static void testDataAdapter()
        {
            try
            {
                MySqlClientFactory factory = MySqlClientFactory.Instance;
                DbConnection conn = factory.CreateConnection();
                conn.ConnectionString = 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 t12345 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++访问:
#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 char * 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 = mysql_stmt_init(mysql_);
    my_bool true_value= 1;
    mysql_stmt_attr_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(bind));
    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;
}

DBCP连接池的最简单应用(用于ORACLE数据库)

鉴于有人问起DBCP直接用于JDBC连接的问题,我做了一个最简单的示例。所有资源来源于网上。它不需要什么Web容器,就是一简单的控制台应用。 

资源: 
http://apache.etoak.com//commons/pool/binaries/commons-pool-1.5.6-bin.zip 
http://labs.renren.com/apache-mirror//commons/dbcp/binaries/commons-dbcp-1.4-bin.zip 
http://download.java.net/maven/1/javaee/jars/javaee-api-5.jar 
当然,还有oracle jdbc要用的ojdbc14.jar (适用于oracle9i及以上版本) 

工程文件:放到这里了。http://dl.iteye.com/topics/download/210279f0-f752-37a6-969f-d58ba13cc394 

数据库连接信息: 
jdbc:oracle:thin:scott/tiger@sean-m700:1521:ora92 
sean-m700是主机名,ora92是oracle数据库的instance ID. 我手头的机器上没有安装oracle数据库,用的是很早以前的一个oracle9.2的拷贝,重新安装实例和相应服务得来的。 

源码如下:借化献佛,源码也是从网上得来的。(http://svn.apache.org/viewvc/commons/proper/dbcp/trunk/doc/BasicDataSourceExample.java?revision=1100136&view=markup) 
Java代码  收藏代码
  1. /* 
  2. // 
  3. 33  // Here's a simple example of how to use the BasicDataSource. 
  4. 34  // 
  5. 35   
  6. 36  // 
  7. 37  // Note that this example is very similiar to the PoolingDriver 
  8. 38  // example. 
  9. 39   
  10. 40  // 
  11. 41  // To compile this example, you'll want: 
  12. 42  //  * commons-pool-1.5.6.jar 
  13. 43  //  * commons-dbcp-1.3.jar (JDK 1.4-1.5) or commons-dbcp-1.4 (JDK 1.6+) 
  14. 44  //  * j2ee.jar (for the javax.sql classes) 
  15. 45  // in your classpath. 
  16. 46  // 
  17. 47  // To run this example, you'll want: 
  18. 48  //  * commons-pool-1.5.6.jar 
  19. 49  //  * commons-dbcp-1.3.jar (JDK 1.4-1.5) or commons-dbcp-1.4 (JDK 1.6+) 
  20. 50  //  * j2ee.jar (for the javax.sql classes) 
  21. 51  //  * the classes for your (underlying) JDBC driver 
  22. 52  // in your classpath. 
  23. 53  // 
  24. 54  // Invoke the class using two arguments: 
  25. 55  //  * the connect string for your underlying JDBC driver 
  26. 56  //  * the query you'd like to execute 
  27. 57  // You'll also want to ensure your underlying JDBC driver 
  28. 58  // is registered.  You can use the "jdbc.drivers" 
  29. 59  // property to do this. 
  30. 60  // 
  31. 61  // For example: 
  32. 62  //  java -Djdbc.drivers=oracle.jdbc.driver.OracleDriver \ 
  33. 63  //       -classpath commons-pool-1.5.6.jar:commons-dbcp-1.4.jar:j2ee.jar:oracle-jdbc.jar:. \ 
  34. 64  //       PoolingDataSourceExample 
  35. 65  //       "jdbc:oracle:thin:scott/tiger@myhost:1521:mysid" 
  36. 66  //       "SELECT * FROM DUAL" 
  37. */  
  38. /* 
  39. The Oracle connection URL for the thin client-side driver ojdbc14.jar has the following format: 
  40. jdbc:oracle:thin:[user/password]@[host][:port]:SID 
  41. jdbc:oracle:thin:[user/password]@//[host][:port]/SID 
  42.  
  43.   user - The login user name defined in the Oracle server. 
  44.  
  45.   password - The password for the login user. 
  46.  
  47.   host - The host name where Oracle server is running.  
  48.          Default is 127.0.0.1 - the IP address of localhost. 
  49.  
  50.   port - The port number where Oracle is listening for connection. 
  51.          Default is 1521. 
  52.  
  53.   SID  - System ID of the Oracle server database instance.  
  54.          SID is a required value. By default, Oracle Database 10g Express  
  55.          Edition creates one database instance called XE. 
  56. */  
  57.   
  58. import org.apache.commons.dbcp.BasicDataSource;  
  59. import javax.sql.*;  
  60. import java.sql.*;  
  61.   
  62. public class TestDataSource  
  63. {  
  64.   
  65.     /** 
  66.      * @param args 
  67.      */  
  68.     public static void main(String[] args)  
  69.     {  
  70.         System.out.println("Setting up data source.");  
  71.         String url = "jdbc:oracle:thin:scott/tiger@sean-m700:1521:ora92";  
  72.         DataSource dataSource = setupDataSource(url);  
  73.         System.out.println("Done...");  
  74.   
  75.         // Now, we can use JDBC DataSource as we normally would.  
  76.         //  
  77.         Connection conn = null;  
  78.         Statement stmt = null;  
  79.         ResultSet rset = null;  
  80.   
  81.         try {  
  82.             System.out.println("Creating connection.");  
  83.             conn = dataSource.getConnection();  
  84.             System.out.println("Creating statement.");  
  85.             stmt = conn.createStatement();  
  86.             System.out.println("Executing statement.");  
  87.             rset = stmt.executeQuery("select 1 from DUAL");  
  88.             System.out.println("Results:");  
  89.             int numcols = rset.getMetaData().getColumnCount();  
  90.             while(rset.next()) {  
  91.                 for(int i=1;i<=numcols;i++) {  
  92.                     System.out.print("\t" + rset.getString(i));  
  93.                 }  
  94.                 System.out.println("");  
  95.             }  
  96.         } catch(SQLException e) {  
  97.             e.printStackTrace();  
  98.         } finally {  
  99.             try { if (rset != null) rset.close(); } catch(Exception e) { }  
  100.             try { if (stmt != null) stmt.close(); } catch(Exception e) { }  
  101.             try { if (conn != null) conn.close(); } catch(Exception e) { }  
  102.         }  
  103.     }  
  104.   
  105.     public static DataSource setupDataSource(String connectURI) {  
  106.         BasicDataSource ds = new BasicDataSource();  
  107.         ds.setDriverClassName("oracle.jdbc.driver.OracleDriver");  
  108.         ds.setUsername("scott");  
  109.         ds.setPassword("tiger");  
  110.         ds.setUrl(connectURI);  
  111.         return ds;  
  112.     }  
  113.   
  114.     public static void printDataSourceStats(DataSource ds) {  
  115.         BasicDataSource bds = (BasicDataSource) ds;  
  116.         System.out.println("NumActive: " + bds.getNumActive());  
  117.         System.out.println("NumIdle: " + bds.getNumIdle());  
  118.     }  
  119.   
  120.     public static void shutdownDataSource(DataSource ds) throws SQLException {  
  121.         BasicDataSource bds = (BasicDataSource) ds;  
  122.         bds.close();  
  123.     }  
  124.   
  125. }  

源码下载地址:
http://dl.iteye.com/topics/download/210279f0-f752-37a6-969f-d58ba13cc394