更新:这个答案在过去没有的一件事是链接到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);
}
}
Run Code Online (Sandbox Code Playgroud)
其中很多都来自我之前写过的另一个答案,但它详细介绍了您的具体问题:
原答案:
这听起来像或多或少需要从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();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11033 次 |
| 最近记录: |