使用 C# 连接数据库

Connecting with the database using C#

我正在尝试从数据库中获取数据,但每次都出现下一个错误:

No se controló System.NullReferenceException HResult=-2147467261
Message=Referencia a objeto no establecida como instancia de un objeto. Source=ImeApps StackTrace: en ComunCD.getConexionIRATI() en C:\Desarrollo\VisualStudio2010\ImeApps\ImeApps\ComunCD.cs:línea 64 en EmpresasCD.getEmpresas() en C:\Desarrollo\VisualStudio2010\ImeApps\ImeApps\EmpresasCD.cs:línea 41 en ImeApps.Principal.abrirSeleccionEmpresaEspera() en C:\Desarrollo\VisualStudio2010\ImeApps\ImeApps\Principal.cs:línea 92 en ImeApps.Principal.abrirSeleccionEmpresa() en C:\Desarrollo\VisualStudio2010\ImeApps\ImeApps\Principal.cs:línea 82 en ImeApps.Principal.menuItem4_Click(Object sender, EventArgs e) en C:\Desarrollo\VisualStudio2010\ImeApps\ImeApps\Principal.cs:línea 77 en System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e) en System.Windows.Forms.ToolStripMenuItem.OnClick(EventArgs e) en System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e) en System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e) en System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met) en System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met) en System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea) en System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) en System.Windows.Forms.Control.WndProc(Message& m) en System.Windows.Forms.ScrollableControl.WndProc(Message& m) en System.Windows.Forms.ToolStrip.WndProc(Message& m) en System.Windows.Forms.MenuStrip.WndProc(Message& m) en System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) en System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) en System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) en System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) en System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) en System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) en System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) en System.Windows.Forms.Application.Run(Form mainForm) en ImeApps.Program.Main() en C:\Desarrollo\VisualStudio2010\ImeApps\ImeApps\Program.cs:línea 16 en System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) en System.AppDomain.nExecuteAssembly(RuntimeAssembly assembly, String[] args) en System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel) en System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly() en System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData) en System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext) en System.Activator.CreateInstance(ActivationContext activationContext) en Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone() en System.Threading.ThreadHelper.ThreadStart_Context(Object state) en System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) en System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) en System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) en System.Threading.ThreadHelper.ThreadStart() InnerException:

我正在做的是:

public class ComunCD
    {
    private static SqlConnection _sqlConnectionIRATI;

    public static void conectarBDIRATI()
        {
            _sqlConnectionIRATI = new SqlConnection(ConfigurationSettings.AppSettings["CONEXION_IRATI"].ToString());
            _sqlConnectionIRATI.Open();
        }

    public static SqlConnection getConexionIRATI()
    {
        if (_sqlConnectionIRATI == null)
        {
            //conectarBDIRATI();
        }
        if (_sqlConnectionIRATI.State != ConnectionState.Open) // HERE I GET THE ERROR
        {
            _sqlConnectionIRATI.Open();
        }
        return _sqlConnectionIRATI;
    }

我做错了什么?提前致谢!

如果 _sqlConnectionIRATInull 你不应该测试 State: 添加 else:

    if (_sqlConnectionIRATI == null)
    {
        //conectarBDIRATI();
    }
    else if (_sqlConnectionIRATI.State != ConnectionState.Open) 
    {
        _sqlConnectionIRATI.Open();
    }

或者您应该创建一个实例:

    // If _sqlConnectionIRATI is null, we create it 
    if (_sqlConnectionIRATI == null)
      conectarBDIRATI();

    // _sqlConnectionIRATI is guaranteed to be not null: 
    if (_sqlConnectionIRATI.State != ConnectionState.Open)  
      _sqlConnectionIRATI.Open();