Can't connect to SQL Server CE database

℡╲_俬逩灬. 提交于 2019-12-24 08:28:36

问题


I have the following code, just to test connection:

public void Test()
{
    SqlCeConnection conn = new SqlCeConnection(@"Data Source=/Application/Database.sdf;");
    try
    {
        conn.Open();
        label1.text = "Connection!";
    }
    catch (Exception ee)
    {
        label1.text = "No connection!";
    }
}

When trying to connect to this database, the application throws an exception at conn.Open() saying

SqlCeException was unhandled

and nothing more. The exception message is blank, so I'm having a hard time figuring out what went wrong.

The database file is there, and the application returns true with

File.Exist(@"/Application/Database.sdf");

so it does have access to the file.

I'm probably doing something really wrong here, can anyone help me out with this?

I'm using Compact Framework 2.0 on Windows CE 5, and the application in question is an existing one. I'm trying to add a database to it so I can load large amounts of data much more easier.


回答1:


What Erik is saying is change your code to this:

public void Test()
{
  SqlCeConnection conn = new SqlCeConnection(@"Data Source=/Application/Database.sdf;");
  try
  {
    conn.Open();
    label1.text = "Connection!";
  }
  catch (SqlCeException ee)  // <- Notice the use of SqlCeException to read your errors
  {
    SqlCeErrorCollection errorCollection = ee.Errors;

    StringBuilder bld = new StringBuilder();
    Exception inner = ee.InnerException;

    if (null != inner) 
    {
      MessageBox.Show("Inner Exception: " + inner.ToString());
    }
    // Enumerate the errors to a message box.
    foreach (SqlCeError err in errorCollection) 
    {
      bld.Append("\n Error Code: " + err.HResult.ToString("X")); 
      bld.Append("\n Message   : " + err.Message);
      bld.Append("\n Minor Err.: " + err.NativeError);
      bld.Append("\n Source    : " + err.Source);

      // Enumerate each numeric parameter for the error.
      foreach (int numPar in err.NumericErrorParameters) 
      {
        if (0 != numPar) bld.Append("\n Num. Par. : " + numPar);
      }

      // Enumerate each string parameter for the error.
      foreach (string errPar in err.ErrorParameters) 
      {
        if (String.Empty != errPar) bld.Append("\n Err. Par. : " + errPar);
      }

    }
    label1.text = bld.ToString();
    bld.Remove(0, bld.Length);
  }
}

The generic Exception you are catching right now can not give you the details of the SqlCeException.



来源:https://stackoverflow.com/questions/16671068/cant-connect-to-sql-server-ce-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!