C#连接数据库是一项非常重要的任务,在软件开发中,我们通常需要将数据存储到数据库中,并且需要使用C#代码在应用程序中与数据库进行交互。在本文中,我们将学习如何使用C#连接到数据库,以及如何完成常见的增删改查操作。

1.连接数据库

首先要连接数据库,需要使用System.Data.SqlClient 命名空间中的SqlConnection类。下面是一个连接到Microsoft SQL
Server数据库的基本示例:
using System.Data.SqlClient; string connectionString = "Data
Source=myServerAddress;Initial Catalog=myDataBase; User
ID=myUsername;Password=myPassword;"; SqlConnection connection = new
SqlConnection(connectionString); try { //打开数据库连接 connection.Open(); //执行数据库操作
//... } catch (Exception ex) { //处理异常 Console.WriteLine(ex.Message); } finally
{ //关闭数据库连接 connection.Close(); }

在上述代码中,我们定义了一个连接字符串,其中包含数据库的服务器名称、数据库名称、用户名和密码等信息。然后,我们使用SqlConnection类创建了一个connection对象,并使用Open方法打开数据库连接,连接成功后即可执行相关操作。

2.增加数据

要将数据添加到数据库中,需要使用SqlCommand类和ExecuteNonQuery方法。下面是将一条新的学生信息添加到学生表中的示例:
using System.Data.SqlClient; string connectionString = "Data
Source=myServerAddress;Initial Catalog=myDataBase; User
ID=myUsername;Password=myPassword;"; SqlConnection connection = new
SqlConnection(connectionString); try { //打开数据库连接 connection.Open(); //定义SQL语句
string sql = "INSERT INTO Students (Name, Age, Gender) VALUES ('John', 20,
'Male');"; //创建SqlCommand对象 SqlCommand command = new SqlCommand(sql,
connection); //执行SQL语句 int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("Rows Affected: " + rowsAffected); } catch (Exception ex) {
//处理异常 Console.WriteLine(ex.Message); } finally { //关闭数据库连接 connection.Close();
}

在上述代码中,我们成功连接到数据库,并使用SqlCommand类定义了一条SQL语句。然后,我们创建了一个SqlCommand对象,并将SQL语句和数据库连接作为参数传递给它。接着,我们调用ExecuteNonQuery方法来执行SQL语句并返回受影响的行数。

3.删除数据

要从数据库中删除数据,可以使用相同的方式,指定要删除的数据行,并使用DELETE命令。下面是从学生表中删除指定姓名的学生信息的示例:
using System.Data.SqlClient; string connectionString = "Data
Source=myServerAddress;Initial Catalog=myDataBase; User
ID=myUsername;Password=myPassword;"; SqlConnection connection = new
SqlConnection(connectionString); try { //打开数据库连接 connection.Open(); //定义SQL语句
string sql = "DELETE FROM Students WHERE Name = 'John';"; //创建SqlCommand对象
SqlCommand command = new SqlCommand(sql, connection); //执行SQL语句 int
rowsAffected = command.ExecuteNonQuery(); Console.WriteLine("Rows Affected: " +
rowsAffected); } catch (Exception ex) { //处理异常 Console.WriteLine(ex.Message); }
finally { //关闭数据库连接 connection.Close(); }
在上代码中,我们使用相同的方法连接到数据库,并使用DELETE命令从学生表中删除名为“John”的学生信息。

4.更新数据

要更新数据库中的数据,可以使用UPDATE命令。下面是一个示例,在学生表中将指定学生的年龄更新为新的值:
using System.Data.SqlClient; string connectionString = "Data
Source=myServerAddress;Initial Catalog=myDataBase; User
ID=myUsername;Password=myPassword;"; SqlConnection connection = new
SqlConnection(connectionString); try { //打开数据库连接 connection.Open(); //定义SQL语句
string sql = "UPDATE Students SET Age = 21 WHERE Name = 'John';";
//创建SqlCommand对象 SqlCommand command = new SqlCommand(sql, connection);
//执行SQL语句 int rowsAffected = command.ExecuteNonQuery(); Console.WriteLine("Rows
Affected: " + rowsAffected); } catch (Exception ex) { //处理异常
Console.WriteLine(ex.Message); } finally { //关闭数据库连接 connection.Close(); }
在上述代码中,我们使用UPDATE命令将名为“John”的学生的年龄更新为21。

5.查询数据

要从数据库中查询数据,可以使用SELECT命令以及其他命令。下面是一个示例,在学生表中查询所有学生信息的示例:
using System.Data.SqlClient; string connectionString = "Data
Source=myServerAddress;Initial Catalog=myDataBase; User
ID=myUsername;Password=myPassword;"; SqlConnection connection = new
SqlConnection(connectionString); try { //打开数据库连接 connection.Open(); //定义SQL语句
string sql = "SELECT * FROM Students;"; //创建SqlCommand对象 SqlCommand command =
new SqlCommand(sql, connection); //执行SQL语句 SqlDataReader dataReader =
command.ExecuteReader(); //遍历查询结果 while (dataReader.Read()) {
Console.WriteLine("{0}\t{1}\t{2}", dataReader["Name"], dataReader["Age"],
dataReader["Gender"]); } //关闭DataReader dataReader.Close(); } catch (Exception
ex) { //处理异常 Console.WriteLine(ex.Message); } finally { //关闭数据库连接
connection.Close(); }

在上述代码中,我们使用SELECT命令来查询学生表中的所有学生信息。我们创建了一个SqlDataReader实例,并使用其Read方法遍历查询结果,最后调用Close方法关闭它。

总结

在C#中连接数据库,我们需要使用System.Data.SqlClient命名空间中的SqlConnection、SqlCommand和SqlDataReader等类。连接数据库时,需要指定数据库连接字符串,并确保在使用SqlCommand时,提供正确的SQL语句和连接对象。使用这些类,我们可以轻松地执行常见的增删改查操作,以及许多其他操作。掌握数据库连接的方法可以使我们能够更轻松地开发出优秀的C#应用程序。

技术
今日推荐
PPT
阅读数 131
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信