C# 使用c在SQL中插入数据表
如何使用c在SQL中插入datatable的值?第二个问题是如何将SQL表复制到datatable变量中?我会先读一读。更新:这个答案过去没有的一件事是指向SQL和数据库新手信息的链接,因此,我将在这里放置一些相关链接,以便您或其他任何人都可以学习他们的SQL和其他数据库设计技能 更新2:以下是填充数据表的示例:C# 使用c在SQL中插入数据表,c#,sql,C#,Sql,如何使用c在SQL中插入datatable的值?第二个问题是如何将SQL表复制到datatable变量中?我会先读一读。更新:这个答案过去没有的一件事是指向SQL和数据库新手信息的链接,因此,我将在这里放置一些相关链接,以便您或其他任何人都可以学习他们的SQL和其他数据库设计技能 更新2:以下是填充数据表的示例: //Namespace References using System.Data; using System.Data.SqlClient /// <summary> /
//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到SQL,但您也可以了解ADO.NET更基本的底层框架,这将使您了解它的基本工作原理
此外,您还可以使用此网站为C编写许多不同的数据库教程
编辑:来自和的更多信息
编辑2:如果您对上面提到的Linq到SQL之类的东西感兴趣,这里有一些来自和的教程
编辑3:其他人也会建议使用ADO.NET实体框架。对于仍然需要掌握使用数据库的基础知识的初学者,我不一定建议这样做。以下是来自
这是一个简单的例子,直接从上面给出的C站链接中提取
清单1。使用SqlConnection
对于这两种情况,您都需要一个相关的数据适配器,例如
我建议你找一本好的ADO.NET书籍或教程——它一定在那里。或者,还有一些关于和的MSDN文章。我发誓我从这个答案中获得了比我想象的更多的吸引力。它似乎创造了奇迹。对于这个答案,我可能应该再修改一点,这样它就可以显示如何填充数据表了。你在面对OP这部分令人眼花缭乱的无知时的耐心是典型的!我很少发现自己有这样的耐心+1cereburs:这篇文章是从我以前的答案复制/粘贴的,并添加了检索数据表的位。这篇文章中的工作量应该除以已经完成的OP的数量,在这个计算中,OP的数量等于…4
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();
}
}
}
}