简体   繁体   中英

Can't connect to SQL Server CE database

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM