在C#中连接SQL数据库,使用ADO.NET库中的SqlConnection类和SqlCommand类。本篇介绍如何连接到SQL Server数据库并执行一个简单的查询。
首先,确保项目已经引入了System.Data.SqlClient这个命名空间。
完整示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace LinkDatabase
{
internal class Program
{
static void Main(string[] args)
{
// 连接字符串,这里替换成你的数据库信息
string connectionString = "Data Source=192.168.1.2;Initial Catalog=School;User ID=sa;Password=00000";
// 创建SqlConnection对象
using (SqlConnection connection = new SqlConnection(connectionString))
{
// 打开连接
connection.Open();
// SQL查询语句,这里可以替换成你自己的查询
string sql = "SELECT * FROM SchoolInfo";
// 创建SqlCommand对象
using (SqlCommand command = new SqlCommand(sql, connection))
{
// 执行查询,并将结果存储在SqlDataReader对象中
using (SqlDataReader reader = command.ExecuteReader())
{
// 读取结果并打印
while (reader.Read())
{
Console.WriteLine("{0}, {1}", reader[0], reader[1]);
}
}
}
}
}
}
}
这个例子是一个最基础的数据库连接和查询的例子。在实际开发中,可能需要考虑更多其他的因素,例如错误处理、数据库连接的关闭和重用、参数化查询等等。
本文暂时没有评论,来添加一个吧(●'◡'●)