基於MySQL Adapter完成資料的增刪和修改操作

iamzxf發表於2015-06-18


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Data;


namespace dataAdapter
{
    class Program
    {
        static void Main(string[] args)
        {
            string constr = "server=127.0.0.1; user=root; password=root;database=users;";
            MySqlConnection mycon = new MySqlConnection(constr);

            string cmdstr = "select id, name from user";
            MySqlCommand mycmd = new MySqlCommand(cmdstr, mycon);

            MySqlDataAdapter myada = new MySqlDataAdapter(mycmd);

            DataSet ds = new DataSet();
            myada.Fill(ds);

            DataTable dt = ds.Tables[0];

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                Console.WriteLine("id:{0}, name:{1}",dt.Rows[i]["id"].ToString(), dt.Rows[i][1].ToString());
            }

            MySqlCommandBuilder mcb = new MySqlCommandBuilder(myada);

            dt.Rows[0]["id"] = "00100";

            DataRow dr = ds.Tables[0].NewRow();
            dr["id"] = "123";
            dr["name"] = "zxf";

            ds.Tables[0].Rows.Add(dr);
            
            myada.Update(ds, ds.Tables[0].ToString());
            ds.Tables[0].AcceptChanges();

            Console.WriteLine("==================");

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                Console.WriteLine("id:{0}, name:{1}", dt.Rows[i]["id"].ToString(), dt.Rows[i][1].ToString());
            }

            Console.ReadLine();
            mycon.Close();
        }
    }
}



相關文章