Click here to Skip to main content
15,898,222 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear Expert,

I'm new to C#. My requirement is to create a DB file (in local system) dynamically & do operation like set & get. I'm able to create .sdf file dynamically and successfully able to read. but while inserting data in .sdf file, its not working properly.

The way i created .sdf file is
Add->NewItem->Data->LocalDatabase through sloution explorer.

Below I've updated my code (created 4 console based app for testing purpose). Please let me know what is the wrong in the code.



C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data.SqlServerCe;
using System.Data.SqlClient;

namespace ConsoleApplication2
{
    class Program
    {
        static public void ReadData()
        {
            string connStr = "Data Source = TempDB.sdf; Password =";

            //if (!File.Exists("DBName.sdf"))
            {
                SqlCeConnection conn = new SqlCeConnection(connStr);
                try
                {
                    SqlCeEngine engine = new SqlCeEngine(connStr);
                   
                    conn.Open();

                    SqlCeCommand cmd = conn.CreateCommand();
                    
                    cmd.CommandText = "SELECT * FROM TestTable WHERE Name = 'Krishna'";
                    SqlCeDataReader myReader = cmd.ExecuteReader();

                    while (myReader.Read())
                    {
                        string strGroup = myReader.GetString(1);
                        
                        int ll = 0;
                        ll++;
                    }

                    

                }
                catch (SqlException ex)
                //catch(Exception)
                {
                    string strMessage = "\nFailed to Read ***";
                    strMessage += ex.Message;
                    // Log the exception
                    Console.WriteLine(strMessage);
                }
                finally
                {
                    conn.Close();
                }
            } 
        }

        static public void WriteData()
        {
            string connStr = "Data Source = TempDB.sdf;";

            //if (!File.Exists("DBName.sdf"))
            {
                SqlCeConnection conn = new SqlCeConnection(connStr);
                conn.Open();
                SqlCeCommand cmd = new SqlCeCommand("INSERT INTO TestTable ([Name], [Group]) Values('Krishna', 'D1')", conn);
                try
                {
                    int iRes = cmd.ExecuteNonQuery();
                    int t = 0;
                    t++;
                }
                catch (Exception)
                {
                    Console.WriteLine("\nFailed to Write\n");
                }
                conn.Close();
            }
        }

        static void Main(string[] args)
        {
            // Write data
            WriteData();

            // Read Data
            ReadData();
        }
    }
}



Thank you all in advance.
Posted
Comments
Sandeep Mewara 20-Apr-12 0:19am    
Care to elaborate 'its not working properly.'?
vidiking 20-Apr-12 5:01am    
I m sorry. Actually I am able to read but not able to insert in the .sdf file.

1 solution

The chances are that the Connection.OPen is throwing an exception, probably because it can't find your DB. Try specifying the path instead of relying on the current folder.

BTW: You should Dispose SqlCeCommand and SqlCeConnection objects as they are scarce resources, unles you keep the Connection open for the life of the application (which can be ok with a SqlCe database, but even then can cause problems with backup software.)
 
Share this answer
 
Comments
vidiking 20-Apr-12 4:57am    
Thank you OriginalGriff for reply.

The way i created TempDB.sdf file is
Add->NewItem->Data->LocalDatabase through solution explorer (like right click on solution and add new file).

N.B. : I'm not able to update the project as my company has restricted for attachment and upload in net.
OriginalGriff 20-Apr-12 5:07am    
That is probably your problem: check your DB properties in the properties pane - it will give you the current path and also a Build Action and Copy to Output Directory option. I would strongly suggest that you move the DB to the Local- or Common- ApplicationData directory instead, and access it from there.

But check first, that that is your problem - look at the exception: what is the error message?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900