【问题标题】:call database connection variables from different classes [closed]从不同的类调用数据库连接变量[关闭]
【发布时间】:2014-02-27 14:42:18
【问题描述】:

我从类开始,现在我正在处理一个项目,该项目涉及放置在根目录不同文件夹中的多个类,并且每个类都连接到同一个数据库。

有没有办法在某处存储连接变量并在每个类中获取它们? (就像一个包含选项)。

一直在阅读有关 Customer 类(这是我的示例)扩展 myvariables 的信息,但我不知道这是否是最佳实践。

你能给我一个提示吗?

【问题讨论】:

    标签: php database class


    【解决方案1】:

    您可以创建一个静态类来为您完成所有数据库工作,并公开您需要的方法。

    public static class DatabaseUtils
    {
        private const string ConnectionString = "...";
    
        public static int GetCustomerId(string firstName, string lastName)
        {
            try
            {
                using (var connection = new SqlConnection(ConnectionString))
                using (var command = new SqlCommand("sql stuff"))
                {
                    var result = command.ExecuteScalar();
                    if (result == DBNull.Value)
                        return -1;
    
                    return (int) result;
                }
            }
            catch (Exception ex)
            {
                // Log errors  + ex
            }
        }
    
        // Other methods to interact with the database
    }
    

    然后您可以调用如下方法:

    int id = DatabaseUtils.GetCustomerId("My", "Name");
    

    如果这最终将成为一个已部署的应用程序,您可能需要考虑将连接字符串存储在 app.config 中,以便无需重新编译应用程序即可对其进行更改。

    【讨论】:

    • OP 说的是 php,对吧?
    • 哇,他做到了。我正在阅读 C# 帖子,然后遇到了这个。
    • 看来他对此很满意.. 所以,就这样吧:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 2011-01-08
    • 2011-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多