【小编教程】深入探索ADO.NET:C#编程中的数据操作进阶(六)
发布时间:2024-07-10 14:00:13 所属栏目:MsSql教程 来源:DaWei
导读: 6. 使用ADO.NET进行C#编程
在使用C#进行ADO.NET编程时,我们可以使用System.Data.SqlClient命名空间中的类来连接、执行查询和关闭数据库连接。以下是一个简单的示
在使用C#进行ADO.NET编程时,我们可以使用System.Data.SqlClient命名空间中的类来连接、执行查询和关闭数据库连接。以下是一个简单的示
6. 使用ADO.NET进行C#编程 在使用C#进行ADO.NET编程时,我们可以使用System.Data.SqlClient命名空间中的类来连接、执行查询和关闭数据库连接。以下是一个简单的示例,展示了如何使用ADO.NET连接MSSQL数据库、执行登录操作以及根据姓名查询数据: ```csharp using System; using System.Data; using System.Data.SqlClient; class Program { static void Main(string[] args) { //1.连接数据库 string connectionString = "Data Source=.;Initial Catalog=MySchool;Integrated Security=True"; string username = "your_username"; string password = "your_password"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); 图文无关,原创配图 //2.执行登录操作string sql = "SELECT COUNT(*) FROM users WHERE username = '" + username + "' AND password = '" + password + "'"; using (SqlCommand command = new SqlCommand(sql, connection)) { int count = (int)command.ExecuteScalar(); if (count >0) { Console.WriteLine("登录成功!"); } else { Console.WriteLine("登录失败!"); } } //3. 根据姓名查询数据 string sql2 = "SELECT * FROM students WHERE name LIKE '%丽%'"; using (SqlCommand command2 = new SqlCommand(sql2, connection)) { using (SqlDataReader reader = command2.ExecuteReader()) { while (reader.Read()) { Console.WriteLine(reader[0] + " " + reader[1] + " " + reader[2]); } } } } //4.关闭连接 connection.Close(); } } ``` 在这个示例中,我们首先创建了一个连接字符串,并使用SqlConnection类打开数据库连接。接着,我们使用SqlCommand类执行登录操作和姓名查询操作。我们在使用完毕后关闭数据库连接。 通过这个简单的示例,你可以了解到如何在C#中使用ADO.NET连接MSSQL数据库并进行基本的操作。在实际项目中,你可能需要根据实际需求进行更复杂的查询和操作,但基本思路和方法都是类似的。 (编辑:威海站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐