2013-12-12 101 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(); 
}