Welcome 微信登录

首页 / 数据库 / MySQL / C++和C#访问MySQL的简单代码示例

贴一份示例代码。非常适合于初学者使用。1) C#访问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, 有兴趣的朋友,可以看看这个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
  • 下一页
配置MongoDB集群分片Oracle 用户、角色权限管理上的几个误区相关资讯      MySQL基础教程  C++访问MySQL  C#访问MySQL 
  • MySQL基础教程:关于varchar(N)  (01月22日)
  • MySQL SELECT同时UPDATE同一张表  (02/19/2013 07:20:18)
  • Linux修改MySQL最大并发连接数  (02/15/2013 15:37:21)
  • 高性能MySQL(第3版) 中文PDF带目  (10/26/2014 10:03:50)
  • 如何在MySQL中的获取IP地址的网段  (02/18/2013 12:23:33)
  • MySQL SET类型字段的SQL操作知识  (12/19/2012 12:10:48)
本文评论 查看全部评论 (0)
表情: 姓名: 字数