开发者

SQL Query's in aspx.cs file (backend)

开发者 https://www.devze.com 2023-02-14 15:03 出处:网络
Is it possible to write sql sentences in the ba开发者_如何转开发ck-end? You know when making a dynamic website, there will allways be tons of SQL sentences.

Is it possible to write sql sentences in the ba开发者_如何转开发ck-end?

You know when making a dynamic website, there will allways be tons of SQL sentences. i was wondering if it was possible to just have 2-3 SQL querys in a class file, and write the rest in the back-end?

Maybe like this.

public DataTable SelectAllFrom(string query)
    {
        string query = @"SELECT * FROM ?query";

        using (var cmd = new MySqlCommand(query))
        {
            cmd.Parameters.Add("?query", MySqlDbType.VarChar).Value = query; 
            return objConn.getData(cmd);
        }
    }

AND THEN in the code-behind:

    string query = "tblAA WHERE fldAA=1";
    var list = _objMethods.SelectAllFrom(query).Rows;


Splitting off SELECT * FROM doesn't really save you much repetition, and will cause you trouble if, say, you don't want to SELECT * because of joins or efficiency.

Your desire to avoid repetition in code is admirable, and isolating the mechanics of running a query from the query itself is good. But this is trying a little too hard. In the big picture look at an ORM instead.


You can do it, but it's not great practice. The more spread out your queries are, and the more SQL you mix in with your presentation and business-logic code, the more difficult it is to maintain. Your question makes it sound like you're working with some type of layered/tiered architecture, and those exist for some very good reasons. I would try to avoid peppering your code with SQL without any organization; it might be quick and easy in the short run, but could lead to problems later.


You could do something like that, but it makes it harder to maintain when the query is split across objects. Add in that you have joins and may not want to also include the join queries too. Personally keeping the queries together makes sense and keeps the responsibility with one layer.

Additionally, you can create a helper to make the database object process a lot easier to use.

HTH.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号