C# ApplicationContext 用法

发布于 2024-10-10 05:40:59 字数 2969 浏览 0 评论 0原文

如果我的术语有问题,请抱歉,我是 C# 新手。我正在尝试使用 ApplicationContext 文件来存储 mysql conn 值,例如数据库名、用户名、密码。带有 mysql conn 字符串的类“使用”ApplicationContext 的命名空间,但是当我打印出连接字符串时,这些值正在生成它。

一位朋友说,“我没有初始化它”,但无法留下来扩展“它”是什么。

和“Console.WriteLine(“1”);”在 ApplicationContext.cs 中永远不会出现。我是否需要创建一个 ApplicationContext 对象并对该对象调用 Initialize() ?

感谢您的任何帮助。

ApplicationContext.cs:

namespace NewApplication.Context
{
    class ApplicationContext
    {
        public static string serverName;
        public static string username;
        public static string password;

        public static void Initialize()
        {
            //need to read through config here

            try
            {

                Console.WriteLine("1");
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(".\\Settings.xml");
                XmlNodeList serverNodeList = xDoc.GetElementsByTagName("DatabaseServer");
                XmlNodeList usernameNodeList = xDoc.GetElementsByTagName("UserName");
                XmlNodeList passwordNodeList = xDoc.GetElementsByTagName("Password");

            }
            catch (Exception ex)
            {
                // MessageBox.Show(ex.ToString());
                //TODO: Future write to log file
                username = "user";
                password = "password";
                serverName = "localhost";
            }
        }
    }
}

MySQLManager.cs: 注意:dbname 与您将在代码中看到的用户名相同,我从这样做的朋友那里复制了这个。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data;
using MySql.Data.MySqlClient;
using NewApplication.Context;


namespace NewApplication.DAO
{
    class MySQLManager
    {
        private static MySqlConnection conn;
        public static MySqlConnection getConnection()
        {
            if (conn == null || conn.State == System.Data.ConnectionState.Closed)
            {
                string connStr = "server=" + ApplicationContext.serverName +
                    ";user=" + ApplicationContext.username + ";database=" + ApplicationContext.username + ";port=3306;password=" +
                    ApplicationContext.password + ";";
                conn = new MySqlConnection(connStr);
                try
                {
                    Console.WriteLine("Connecting to MySQL... ");
                    Console.WriteLine("Connection string:  " + connStr + "\n");
                    conn.Open();
                    // Perform databse operations


                    // conn.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
            return conn;
        }
    }
}

并且,感谢您仍然阅读,这是使用前两个文件的代码:

class LogDAO
{
    MySqlConnection conn;

    public LogDAO()
    {
        conn = MySQLManager.getConnection();
}

谢谢, RD42

Apologies if my terminology is off, I'm new to C#. I'm trying to use an ApplicationContext file to store mysql conn values, like dbname, username, password. The class with mysql conn string is "using" the namespace for the ApplicationContext, but when I print out the connection string, the values are making it.

A friend said, "I'm not initializing it" but couldn't stay to expand on what "it" was.

and the "Console.WriteLine("1");" in ApplicationContext.cs never shows up. Do I need to create an ApplicationContext object and the call Initialize() on that object?

Thanks for any help.

ApplicationContext.cs:

namespace NewApplication.Context
{
    class ApplicationContext
    {
        public static string serverName;
        public static string username;
        public static string password;

        public static void Initialize()
        {
            //need to read through config here

            try
            {

                Console.WriteLine("1");
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(".\\Settings.xml");
                XmlNodeList serverNodeList = xDoc.GetElementsByTagName("DatabaseServer");
                XmlNodeList usernameNodeList = xDoc.GetElementsByTagName("UserName");
                XmlNodeList passwordNodeList = xDoc.GetElementsByTagName("Password");

            }
            catch (Exception ex)
            {
                // MessageBox.Show(ex.ToString());
                //TODO: Future write to log file
                username = "user";
                password = "password";
                serverName = "localhost";
            }
        }
    }
}

MySQLManager.cs:
note: dbname is the same as the username as you'll see in the code, I copied this from a friend who does that.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data;
using MySql.Data.MySqlClient;
using NewApplication.Context;


namespace NewApplication.DAO
{
    class MySQLManager
    {
        private static MySqlConnection conn;
        public static MySqlConnection getConnection()
        {
            if (conn == null || conn.State == System.Data.ConnectionState.Closed)
            {
                string connStr = "server=" + ApplicationContext.serverName +
                    ";user=" + ApplicationContext.username + ";database=" + ApplicationContext.username + ";port=3306;password=" +
                    ApplicationContext.password + ";";
                conn = new MySqlConnection(connStr);
                try
                {
                    Console.WriteLine("Connecting to MySQL... ");
                    Console.WriteLine("Connection string:  " + connStr + "\n");
                    conn.Open();
                    // Perform databse operations


                    // conn.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
            return conn;
        }
    }
}

and, thanks for still reading, this is the code that uses the two previous files:

class LogDAO
{
    MySqlConnection conn;

    public LogDAO()
    {
        conn = MySQLManager.getConnection();
}

Thank you,
rd42

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

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

发布评论

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

评论(1

姐不稀罕 2024-10-17 05:40:59

忽略.NET中已经有非常丰富的配置类集,包括用于连接的配置类< /a> 支持加密,您确实需要在某些时候调用 Application.Initialize() 才能填充它的字段。

我应该提到,这看起来像是单例的实现。您可能想阅读 Jon Skeet 关于单例的文章,因为可能有一些您想观看的内容出去。例如,如果两个线程调用 ApplicationContext.Initialize() 会发生什么?多次调用 ApplicationContext.Initialize() 是否合理?

此外,公共字段可能不是一个好主意,尤其是当您有自动实现的属性时可供您使用。

Ignoring that there's already a very rich set of Configuration Classes in .NET including ones for Connections that support encryption, you do need to as some point call Application.Initialize() in order for it fields to be populated.

I should mention that this looks like an implementation of a singleton. You might want to read Jon Skeet's article on singletons because there are probably things you want to watch out for. For example what would happen if two threads called ApplicationContext.Initialize()? Are multiple calls to ApplicationContext.Initialize() even sensible?

Also public fields are probably a bad idea especially when you have automatic implemented properties available to you.

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