c#的mvc框架能自己写DBHlper连接数据库不?感觉mvc的EF好呆?
1条回答 默认 最新
关注让阿豪来帮你解答,本回答参考chatgpt3.5编写提供,如果还有疑问可以评论或留言
在使用C#的MVC框架时,可以自己编写DBHelper类来连接数据库,而不必使用Entity Framework(EF)。 下面是一种常见的使用自定义DBHelper类来连接数据库的方式: 首先,创建一个DBHelper类,用于封装数据库连接和执行SQL语句的方法:using System; using System.Data; using System.Data.SqlClient; public class DBHelper { private string connectionString = "YourConnectionStringHere"; public DataTable ExecuteQuery(string query) { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = new SqlCommand(query, connection); DataTable dt = new DataTable(); dt.Load(command.ExecuteReader()); return dt; } } public int ExecuteNonQuery(string query) { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = new SqlCommand(query, connection); return command.ExecuteNonQuery(); } } }然后,在MVC的Controller中实例化DBHelper类,并调用其方法来连接数据库和执行SQL语句:
public class HomeController : Controller { public ActionResult Index() { DBHelper dbHelper = new DBHelper(); DataTable dt = dbHelper.ExecuteQuery("SELECT * FROM Customers"); // Process the DataTable as needed return View(); } [HttpPost] public ActionResult SaveCustomer(CustomerModel customer) { DBHelper dbHelper = new DBHelper(); int rowsAffected = dbHelper.ExecuteNonQuery("INSERT INTO Customers (Name, Email) VALUES ('" + customer.Name + "', '" + customer.Email + "')"); // Check the rowsAffected value to see if the SQL query was successfully executed return RedirectToAction("Index"); } }在上述代码中,我们创建了一个DBHelper类来连接数据库并执行SQL语句,在Controller中通过实例化DBHelper来调用其方法。这样就能够在MVC框架中自定义数据库连接,而不依赖于Entity Framework。
解决 无用评论 打赏 举报