使用C#开发一个sqlserver增删改查并返回执行结果
以下是一个使用C#开发的sqlserver增删改查,并返回执行结果的示例代码:
using System;
using System.Data.SqlClient;
namespace SqlServerCRUD
{
class Program
{
static void Main(string[] args)
{
string connectionString = "Server=YourServerName;Database=YourDatabaseName;Trusted_Connection=True;";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
// 插入数据
string insertQuery = "INSERT INTO Students (Name, Age, Gender) VALUES ('Tom', 20, 'Male')";
SqlCommand insertCommand = new SqlCommand(insertQuery, connection);
int insertResult = insertCommand.ExecuteNonQuery();
Console.WriteLine("Insert result: " + insertResult);
// 查询数据
string selectQuery = "SELECT * FROM Students";
SqlCommand selectCommand = new SqlCommand(selectQuery, connection);
SqlDataReader reader = selectCommand.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("Name: {0}, Age: {1}, Gender: {2}", reader["Name"], reader["Age"], reader["Gender"]);
}
reader.Close();
// 更新数据
string updateQuery = "UPDATE Students SET Age = 21 WHERE Name = 'Tom'";
SqlCommand updateCommand = new SqlCommand(updateQuery, connection);
int updateResult = updateCommand.ExecuteNonQuery();
Console.WriteLine("Update result: " + updateResult);
// 删除数据
string deleteQuery = "DELETE FROM Students WHERE Name = 'Tom'";
SqlCommand deleteCommand = new SqlCommand(deleteQuery, connection);
int deleteResult = deleteCommand.ExecuteNonQuery();
Console.WriteLine("Delete result: " + deleteResult);
connection.Close();
}
}
}
在上面的示例代码中,我们首先创建了一个SqlConnection对象,然后使用Open方法打开与SQL Server的连接。接下来,我们使用SqlCommand对象执行SQL语句来进行增删改查操作,并使用ExecuteNonQuery方法返回执行结果。最后,我们使用Close方法关闭与SQL Server的连接。
原文地址: https://www.cveoy.top/t/topic/McU 著作权归作者所有。请勿转载和采集!