How do I connect to a SQL database from C#?(如何从 C# 连接到 SQL 数据库?)
问题描述
I am trying to write a local program management and install system for my home network, and I think I've got the technologies nailed down:
- C#/.NET/WPF for the client
- Lua for installation scripting support (through LuaInterface)
- SQL Server Express for maintaining a database of programs
However I'm unsure what specifically I'll use to connect C# to the database. Is there something built into the .NET framework for this? Bonus points if you have a suggestion on what I should use for interacting with said database.
Check out
- Introduction to ADO.NET Tutorial
- ADO.NET Tutorial Lesson 1
- An introduction to ADO.NET
I'm sure there's plenty more out there - just google for "ADO.NET" and "Tutorial" ......
UPDATE:
If you want to connect to your local SQL Server Express, and connect to the "Northwind" database, and read the top 5 customers from the "Customers" table, you'd have to do something like this:
string connectionString = "server=(local)SQLExpress;database=Northwind;integrated Security=SSPI;";
using(SqlConnection _con = new SqlConnection(connectionString))
{
string queryStatement = "SELECT TOP 5 * FROM dbo.Customers ORDER BY CustomerID";
using(SqlCommand _cmd = new SqlCommand(queryStatement, _con))
{
DataTable customerTable = new DataTable("Top5Customers");
SqlDataAdapter _dap = new SqlDataAdapter(_cmd);
_con.Open();
_dap.Fill(customerTable);
_con.Close();
}
}
Now you would have all 5 top customers from your Northwind database in the DataTable and you can inspect them, print them out, manipulate them - whatever you want to do.
That's ADO.NET in action!
As for the details of the connection string - what options you can use and what it should look like, check out the Connection Strings web site - it has tons of examples and explanations.
Marc
这篇关于如何从 C# 连接到 SQL 数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 C# 连接到 SQL 数据库?
基础教程推荐
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- MS Visual Studio .NET 的替代品 2022-01-01