[英]Datatable insertion in SQL using c#
我們如何使用c#在SQL中插入datatable的值? 第二個問題是我們如何將SQL表復制到datatable變量中?
更新 :這個答案在過去沒有的一件事是鏈接到SQL和數據庫新手的信息,所以我也會在這里放一些相關鏈接,以便你(或其他任何人)可以刷新他們的SQL和其他數據庫設計技巧。
更新2 :這是填充數據表的示例:
//Namespace References
using System.Data;
using System.Data.SqlClient
/// <summary>
/// Returns a DataTable, based on the command passed
/// </summary>
/// <param name="cmd">
/// the SqlCommand object we wish to execute
/// </param>
/// <returns>
/// a DataTable populated with the data
/// specified in the SqlCommand object
/// </returns>
/// <remarks></remarks>
public static DataTable GetDataTable(SqlCommand cmd)
{
try
{
// create a new data adapter based on the specified query.
SqlDataAdapter da = new SqlDataAdapter();
//set the SelectCommand of the adapter
da.SelectCommand = cmd;
// create a new DataTable
DataTable dtGet = new DataTable();
//fill the DataTable
da.Fill(dtGet);
//return the DataTable
return dtGet;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
其中很多都來自我之前寫過的另一個答案,但它詳細介紹了您的具體問題:
原答案 :
這聽起來像或多或少需要從C#連接和操作數據庫的基本介紹。 上面的海報說看看LINQ to SQL,但你也可以看看ADO.NET的更基本的底層框架,它將讓你了解它的工作原理。
此外,您可以在此處使用此站點獲取C#的許多不同數據庫教程。
編輯 :來自C#Station , CodeProject和Codersource的更多信息
編輯2 :如果您對其他人如上所述的Linq to SQL感興趣,這里有一些來自C#Corner和C-Sharp Online的教程
編輯3 :其他人也會建議諸如ADO.NET實體框架之類的東西。 對於仍然需要掌握使用數據庫的基礎知識的初學者,我不一定會建議這樣做。 以下是MSDN概述中的一些信息
簡單示例 (直接從上面給出的C#Station鏈接中提取)
清單1.使用SqlConnection
using System;
using System.Data;
using System.Data.SqlClient;
/// <summary>
/// Demonstrates how to work with SqlConnection objects
/// </summary>
class SqlConnectionDemo
{
static void Main()
{
// 1. Instantiate the connection
SqlConnection conn = new SqlConnection(
"Data Source=(local);Initial Catalog=Northwind;
Integrated Security=SSPI");
SqlDataReader rdr = null;
try
{
// 2. Open the connection
conn.Open();
// 3. Pass the connection to a command object
SqlCommand cmd =
new SqlCommand("select * from Customers", conn);
//
// 4. Use the connection
//
// get query results
rdr = cmd.ExecuteReader();
// print the CustomerID of each record
while (rdr.Read())
{
Console.WriteLine(rdr[0]);
}
}
finally
{
// close the reader
if (rdr != null)
{
rdr.Close();
}
// 5. Close the connection
if (conn != null)
{
conn.Close();
}
}
}
}
對於這兩者,您需要一個相關的數據適配器 ,例如SqlDataAdapter
。
我建議你找一本好的ADO.NET書或教程 - 它一定會在那里。 或者,有關於DataAdapters / DataReaders和在ADO.NET中檢索和修改數據的 MSDN文章。
我會讀取ADO.NET和LINQ to SQL作為初學者。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.