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, 有兴趣的朋友,可以看看这个bug是怎么回事 
        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(); 
        } 
    } 

  • 1
  • 2
  • 下一页

相关内容