Search code examples
c#sql-server-ce

Strange C# error while inserting in database


I have 2 forms in my program. I am using a SQL Server Compact 3.5 database file (.sdf) from C#

albums_tbl table has two columns: id, name

In form 1 when I use this code :

private void button1_Click(object sender, EventArgs e)
{
    SqlCeCommand cm = new SqlCeCommand("INSERT INTO albums_tbl(album_name) VALUES (@album_name) ", cn);
    cm.Parameters.AddWithValue("@album_name", textBox1.Text);

    int affectedrows = cm.ExecuteNonQuery();

    if (affectedrows > 0)
    {
         MessageBox.Show("insert shod !");
    }
}

the program inserts well, but when I use the exact code in form 2 it errors this when I want to insert :

enter image description here


Solution

  • You don't open connection yet.

    SqlCeConnection conn = null;
    
    try
    {
        conn = new SqlCeConnection("Data Source = MyDatabase.sdf; Password ='<pwd>'");
        conn.Open();
    
        SqlCeCommand cmd = conn.CreateCommand();
        cmd.CommandText = "INSERT INTO Customers ([Customer ID], [Company Name]) Values('NWIND', 'Northwind Traders')";
    
        cmd.ExecuteNonQuery();
    }
    finally
    {
        conn.Close();
    }
    

    Refer: https://msdn.microsoft.com/en-us/library/system.data.sqlserverce.sqlceconnection(v=vs.100).aspx

    Hope this helps.