2013-12-12 99 views
2

在C#+ SQL Server CE中執行查詢的最佳方法是哪種?我需要創建一個表格,但經過3天的不成功嘗試,我意識到我真的不能爲自己做這件事......所以我在這裏尋求幫助。使用SQL Server CE創建表查詢

我已經試過以下主題:

但我想告訴我異常的所有方面......我很困惑,哪裏是我的錯?

我當前的代碼:

public void Connect() 
{ 
    try 
    { 
     string FileName = "DataBase"; 

     using (SqlCeConnection myConnection = new SqlCeConnection(@"Data Source=|DataDirectory|\" + FileName + ".sdf;Password=Z123")) 
     { 
      string query = "create table EXP(ID int, source int)"; 
      int i; 

      SqlCommand cmd = new SqlCommand(query, connection); 
      cmd.con.open(); 
      i = cmd.ExecuteNonQuery(); 
     } 
    } 
    catch (SqlCeException ae) 
    { 
     MessageBox.Show(ae.Message.ToString()); 
    } 
} 

非常感謝!

+0

什麼'FileName'的價值?如果你從'System.Io.File'中得到它,它已經包含了「.sdf」。此外,無論何時您對異常有疑問,**都會向我們展示異常**。 –

回答

3

如果您使用的是SQL Server CE那麼您需要使用SqlCeCommand(而不是SqlCommand--這是完整的SQL Server)。

因此改變你的代碼:

using (SqlCeConnection myConnection = new SqlCeConnection(@"Data Source=|DataDirectory|\" + FileName + ".sdf;Password=Z123")) 
{ 
    string query = "create table EXP(ID int, source int)"; 

    // use SqlCeCommand here!! Also: use the "myConnection" SqlCeConnection you're 
    // opening at the top - don't use something else..... 
    SqlCeCommand cmd = new SqlCeCommand(query, myConnection); 

    myConnection.open(); 
    cmd.ExecuteNonQuery(); 
    myConnection.Close(); 
}