1. 程式人生 > >將datatable 插入資料庫

將datatable 插入資料庫

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

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // 連線字串
            string cnnString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\jonaszhang\\Downloads\\示例原始碼\\示例原始碼\\第17章\\示例資料庫\\示例資料庫\\TestDB.mdf;Integrated Security=True;Connect Timeout=30
";// "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=F:\\pauls_file\\BOOKCD022619\\示例原始碼\\第17章\\示例資料庫\\示例資料庫\\TestDB.mdf;Integrated Security=True;Connect Timeout=30"; // 建立連線物件 SqlConnection conn = new SqlConnection(cnnString); try {
// 開啟連線 conn.Open(); // 建立命令物件 SqlCommand cmd = conn.CreateCommand(); // 設定SQL語句 cmd.CommandText = "SELECT TOP 10 * FROM products"; // 執行SQL語句並返回資料閱讀器 SqlDataReader reader = cmd.ExecuteReader();
// 讀取每一行資料,並輸出到螢幕上 while (reader.Read()) { Console.WriteLine("產品ID:{0},產品名稱:{1}", reader.GetInt32(0), reader.GetString(1)); } // 關閉閱讀器 reader.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { // 關閉連 conn.Close(); } Console.Read(); } } }
View Code

 

/*

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace jonastrysql
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}


*/



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Collections;
using System.Data;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=JonasTry;Integrated Security=True"; // "Data Source=leaf-home\\sqlserver2005;Initial Catalog=Test;Persist Security Info=True;User ID=site_dev;Password=???";
            using (SqlConnection conn = new SqlConnection(connectString))
            {
                conn.Open();
                Console.Write("ni hao");
               /* SqlCommand sqlCom = new SqlCommand();
                sqlCom.Connection = conn;
                sqlCom.CommandType = CommandType.Text;
                sqlCom.CommandText = "select * from [JonasTry].[DBO].[tb]";
                SqlDataReader tableList = sqlCom.ExecuteReader();

                while (tableList.Read())
                {
                    Console.Write(tableList["A"].ToString()+"\t");
                    Console.Write(tableList["B"].ToString() + "\t");
                    Console.Write("\n");
                }
                tableList.Close();
                */




                //-------- 建立要測試的資料 begin -------------
                DataTable dtNew = new DataTable();
                dtNew.Columns.Add(new DataColumn("A", typeof(int)));
                dtNew.Columns.Add(new DataColumn("B", typeof(string)));

                DataRow dr = dtNew.NewRow();
                dr["A"] = 99;
                dr["B"] = "";
                dtNew.Rows.Add(dr);
                dr = dtNew.NewRow();
                dr["A"] = 101;
                dr["B"] = "";
                dtNew.Rows.Add(dr);
                //-------- 建立要測試的資料 end -------------

                //得到原表結構
                //conn.Open();
                string strSql = "SELECT * FROM dbo.tb WHERE 1=0";
                SqlDataAdapter adapter = new SqlDataAdapter(strSql, conn);
                SqlCommandBuilder builder = new SqlCommandBuilder(adapter);


                DataSet ds = new DataSet();
                adapter.Fill(ds, "flag");
                DataTable table = ds.Tables["flag"];


                //將新資料傳到對應的datatable中
                foreach (DataRow drNew in dtNew.Rows)
                {
                    DataRow row = table.NewRow();
                    foreach (DataColumn dc in table.Columns)
                    {
                        row[dc.ColumnName] = drNew[dc.ColumnName];
                    }
                    table.Rows.Add(row);
                }

                //更新資料庫
                adapter.Update(table);

                //讀取資料庫中的資料
                SqlCommand sqlCom = new SqlCommand();
                sqlCom.Connection = conn;
                sqlCom.CommandType = CommandType.Text;
                sqlCom.CommandText = "select * from [JonasTry].[DBO].[tb]";
                SqlDataReader tableList = sqlCom.ExecuteReader();

                while (tableList.Read())
                {
                    Console.Write(tableList["A"].ToString() + "\t");
                    Console.Write(tableList["B"].ToString() + "\t");
                    Console.Write("\n");
                }
                tableList.Close();
                //讀完了
                Console.Write("\n show finish");
            }
            Console.Read();
        }//end of Main
    }//end of class
}//end of namespace
View Code