如何在 ASP.NET 中连接到数据库?

发布于 2024-08-23 22:23:33 字数 2205 浏览 5 评论 0原文

我从 PHP 迁移到 ASP.NET,其中直接运行查询。因此,我总是在 Page_Load 事件中创建连接,在完成所有需要的操作后将其处置,并使用 NpgsqlCommand 访问数据。 (是的,我在 ASP.NET 应用程序中使用 Postgresql。)

开始学习 ASP.NET MVC 后,我惊讶地发现使用 LINQ to SQL 访问 SQL 是多么容易。但是...它仅适用于 MS SQL。所以我的问题是如何在我的应用程序中实现相同的功能?如何轻松连接数据库?

我编写了自己的包装类来连接到 Postgresql。每桌 1 堂课。

这是 Student 类的一部分:

public class Student : User
{
    private static NpgsqlConnection connection = null;

    private const string TABLE_NAME = "students";

    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Password { get; set; }

    /// <summary>
    /// Updates the student
    /// </summary>
    public void Update()
    {
        Connect();
        Run(String.Format("UPDATE " + TABLE_NAME + " SET first_name='{0}', last_name='{1}', password='{2}' WHERE id={3}", FirstName, LastName, Password, Id));
        connection.Dispose();
    }

    /// <summary>
    /// Inserts a new student
    /// </summary>
    public void Insert()
    {
        Connect();
        Run(String.Format("INSERT INTO " + TABLE_NAME + " (first_name, last_name, password) VALUES ('{0}', '{1}', '{2}')",FirstName, LastName, Password));
        connection.Dispose();
    }

    private static void Run(string queryString)
    {
        NpgsqlCommand cmd = new NpgsqlCommand(queryString, connection);
        cmd.ExecuteScalar();
        cmd.Dispose();
    }

    private static void Connect()
    {
        connection = new NpgsqlConnection(String.Format("Server=localhost;Database=db;Uid=uid;Password=pass;pooling=false"));
        connection.Open();
    }

    //....

因此,正如您所看到的,这里的问题是,对于每个 INSERT、DELETE、UPDATE 请求,我都使用连接到数据库的 Connect() 方法。在我不得不等待 10 分钟才能插入 500 行之前,我没有意识到这是多么愚蠢,因为有 500 个到数据库的连接。

在连接时使用池确实有帮助,但仍然建立连接并让服务器在每个查询期间检查池是愚蠢的。

因此,我决定将 Connection 属性移至静态数据库类,但它也不起作用,因为将此类对象作为连接存储在静态类中是一个非常糟糕的主意。

我真的不知道该怎么办。是的,可以选择在每个 Page_Load 事件中手动创建连接并最终关闭它们,就像我现在所做的那样。

Student student = new Student { FirstName="Bob", LastName="Black" };
NpgsqlConnection connection = ... ;
student.Insert(connection);

但这段代码非常难看。我真的很感谢能在这里帮助我的人。

I moved to ASP.NET from PHP where the queries are run directly. So I always create Connection in the Page_Load Event, dispose it after I do all stuff needed, and access data with NpgsqlCommand. (Yes, I use Postgresql in my ASP.NET applications.)

After starting to learn ASP.NET MVC I was amazed how easy it is to access SQL with the LINQ to SQL thing. But... It works only with MS SQL. So my question is how to implement the same functionality in my applications? How to connect to databases easily?

I wrote my own wrapper classes for connecting to Postgresql. 1 class per a table.

This is a part of the Student class:

public class Student : User
{
    private static NpgsqlConnection connection = null;

    private const string TABLE_NAME = "students";

    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Password { get; set; }

    /// <summary>
    /// Updates the student
    /// </summary>
    public void Update()
    {
        Connect();
        Run(String.Format("UPDATE " + TABLE_NAME + " SET first_name='{0}', last_name='{1}', password='{2}' WHERE id={3}", FirstName, LastName, Password, Id));
        connection.Dispose();
    }

    /// <summary>
    /// Inserts a new student
    /// </summary>
    public void Insert()
    {
        Connect();
        Run(String.Format("INSERT INTO " + TABLE_NAME + " (first_name, last_name, password) VALUES ('{0}', '{1}', '{2}')",FirstName, LastName, Password));
        connection.Dispose();
    }

    private static void Run(string queryString)
    {
        NpgsqlCommand cmd = new NpgsqlCommand(queryString, connection);
        cmd.ExecuteScalar();
        cmd.Dispose();
    }

    private static void Connect()
    {
        connection = new NpgsqlConnection(String.Format("Server=localhost;Database=db;Uid=uid;Password=pass;pooling=false"));
        connection.Open();
    }

    //....

So as you see the problem here is that with every INSERT, DELETE, UPDATE request I'm using Connect() method which connects to the database. I didn't realize how stupid it was before I had to wait for 10 minutes to have 500 rows inserted, as there were 500 connections to the database.

Using pooling while connecting does help, but still making the connection and making the server check the pool during every single query is stupid.

So I decided to move Connection property to a static DB class, and it didn't work either, because it's a really bad idea to store such objects as connections in a static class.

I really don't know what to do know. Yes, there's an option of manullay creating the connections in every Page_Load event and close them in the end like I'm doing it right now.

Student student = new Student { FirstName="Bob", LastName="Black" };
NpgsqlConnection connection = ... ;
student.Insert(connection);

But this code is pretty ugly. I will be really thankful to somebody who can hep me here.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

筱武穆 2024-08-30 22:23:33

我不会推荐这种设计。最好封装每个数据库调用,这意味着每次需要在数据库上执行某些操作时,每个调用都会打开一个新连接。如果没有连接池,这听起来可能效率很低。 ASP.NET 将自动在池中为您重用连接。您设计中的问题是没有任何东西可以保证连接将被关闭。

因此,您应该尝试类似

private static void Insert()
{
    var sql = "Insert Into "....;
    ExecuteActionQuery(sql);
}

private static void ExecuteActionQuery( string query )
{
    using (var conn = new NpgsqlConnection(String.Format(connString))
    {
        conn.Open();
        using ( var cmd = new NpgsqlCommand(query, connection) )
        {
            cmd.ExecuteNonQuery();
        }
    }
}

我通常创建一些封装标准操作的全局函数,以便我只需要传递查询和参数,而我的方法会完成其余的工作。在我的示例中,我的 ExecuteActionQuery 不带参数,但这仅用于演示。

I would not recommend this design. It is better to encapsulate each database call which means each call opens a new connection each time you need to do something on the db. This might sound inefficient if it were not for connection pooling. ASP.NET will reuse connections automatically for you in a pool. The problem in your design is that there is nothing that guarantees that the connection will be closed.

Thus, you should try something like

private static void Insert()
{
    var sql = "Insert Into "....;
    ExecuteActionQuery(sql);
}

private static void ExecuteActionQuery( string query )
{
    using (var conn = new NpgsqlConnection(String.Format(connString))
    {
        conn.Open();
        using ( var cmd = new NpgsqlCommand(query, connection) )
        {
            cmd.ExecuteNonQuery();
        }
    }
}

I typically make a few global functions that encapsulate the standard operations so that I need only pass a query and parameters and my method does the rest. In my example, my ExecuteActionQuery does not take parameters but this was for demonstration only.

挽清梦 2024-08-30 22:23:33

与您的问题并不真正相关,而是另一种解决方案,如果您喜欢 linq to sql,您可以尝试 DBLinq,它为 Postgresql 和其他数据库提供 Linq to SQL 提供程序。

http://code.google.com/p/dblinq2007/

Not really pertaining to your question but another solution, if you like linq to sql, you could try DBLinq which provides a Linq to SQL provider for Postgresql and others databases.

http://code.google.com/p/dblinq2007/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文