Entschuldigung, wenn meine Terminologie aus ist, bin ich neu in C#. Ich versuche, eine ApplicationContext-Datei zu verwenden, um mysql conn-Werte wie DB-Name, Benutzername, Kennwort zu speichern. Die Klasse mit mysql conn string "benutzt" den Namespace für den ApplicationContext, aber wenn ich die Verbindungszeichenfolge ausdrucke, machen die Werte es.C# ApplicationContext Verwendung
Ein Freund sagte: "Ich initialisiere es nicht" aber konnte nicht bleiben, um zu erweitern, was "es" war.
und die "Console.WriteLine (" 1 ");" in ApplicationContext.cs wird nie angezeigt. Muss ich ein ApplicationContext-Objekt und den Aufruf Initialize() für dieses Objekt erstellen?
Danke für jede Hilfe.
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: Anmerkung: DB-Name der gleiche wie der Benutzername ist, wie Sie im Code sehen werden, kopiert ich dies von einem Freund, der das tut.
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;
}
}
}
und dank für noch zu lesen, das ist der Code, der die beiden vorherigen Dateien verwendet:
class LogDAO
{
MySqlConnection conn;
public LogDAO()
{
conn = MySQLManager.getConnection();
}
Danke, rd42
Es gibt bereits eine ApplicationContext-Klasse ... also was versuchst du mit deiner zu machen? http://msdn.microsoft.com/en-us/library/system.windows.forms.applicationcontext.aspx –
Danke, ich werde es untersuchen. – rd42