Reputation: 55
Which is the best way to execute a query in C# + SQL Server CE? I need to create a table, but after 3 days of unsuccessful attempts, I realize that I really can't do it for myself... So I'm here asking for help.
I've tried these topics:
But all ways I tried show me an exception... I'm confused, where is my mistake?
My current code:
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());
}
}
Many thanks!
Upvotes: 2
Views: 3348
Reputation: 754348
If you're using SQL Server CE then you need to use a SqlCeCommand
(not a SqlCommand
- that's for the full-blown SQL Server).
So change your code to:
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();
}
Upvotes: 3