简单向DataTable添加一行,随笔

来源:互联网 发布:php项目 app data 编辑:程序博客网 时间:2024/05/16 05:42
 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace FindDataRow
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建数据库连接字符串
            SqlConnection thisConnection = new SqlConnection(@"Data Source=WENGJIXI;" +
            @"Initial Catalog=NorthWind;" +
            @"Integrated Security=true;");

            //创建DataAdapter对象,表示一组 SQL 命令和一个数据库连接,它们用于填充 DataSet 和更新数据源
            SqlDataAdapter thisAdapter = new SqlDataAdapter("select CustomerID,CompanyName from Customers", thisConnection);
            //创建一个SQL命名,关联DataAdapter对象。
            SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter);
           
            //创建DataSet对象
            DataSet thisDataSet=new DataSet();
            thisAdapter.Fill(thisDataSet, "Customers");
            Console.WriteLine("#在向Customers表添加一行前,表里面行的个数:{0}", thisDataSet.Tables["Customers"].Rows.Count);

            //下面的方法也可以用thisAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;替换
            DataColumn[] keys = new DataColumn[1];//因为主键可以有多列,所以用DataColumn数组。
            keys[0] = thisDataSet.Tables["Customers"].Columns["CustomerID"];
            thisDataSet.Tables["Customers"].PrimaryKey = keys;
            @writes:
            Console.WriteLine("请输入你的公司ID");
            string writeData = Console.ReadLine();
            //使用DataRow对象的Find()方法查询XICO是否存在行中。
            DataRow findRow = thisDataSet.Tables["Customers"].Rows.Find(writeData);
            if (findRow == null)
            {
                Console.WriteLine("数据没有在Customers表中,可以向其中添加数据");
                DataRow newRow = thisDataSet.Tables["Customers"].NewRow();
                newRow["CustomerID"] = writeData;
                Console.WriteLine("请输入你的公司名字");
                string companyName = Console.ReadLine();
                newRow["CompanyName"] = companyName;
                thisDataSet.Tables["Customers"].Rows.Add(newRow);
                if ((findRow = thisDataSet.Tables["Customers"].Rows.Find(writeData)) != null)
                    Console.WriteLine("成功向表添加一行数据");

            }
            else
            {
                Console.WriteLine("数据已经在Customers表中");
                goto writes;
            }

            //更新数据库
            thisAdapter.Update(thisDataSet, "Customers");
            Console.WriteLine("#在向Customers表添加一行后,表里面行的个数:{0}", thisDataSet.Tables["Customers"].Rows.Count);

            //关闭数据库连接
            thisConnection.Close();
            Console.ReadLine();
        }
    }
}

原创粉丝点击