hi there,
I am trying to make my service to insert to a database when it starts as follows :

protected override void OnStart(string[] args)
        {
            base.OnStart(args);
            string query;
            id += 1;
            
            SqlCommand comm;
            conn = new SqlConnection("my connection string");
            query = "insert into myTable values('" + id + "'lamya'" + "')";
            comm = new SqlCommand(query, conn);
            
                try
                {
                    conn.Open();

                    while (id >= 120)
                    {
                        comm.ExecuteScalar();
                        query = "insert into myTable values('" + id + "'lamya'" + "')";
                        comm = new SqlCommand(query, conn);
                        id++; 
                                                                        
                    }
                    conn.close();

                }
                catch (Exception ex)
                {
                    //throw ex;
                }

                          
        }

after adding an installer and installing the service using the Installutil.exe

when I start the service from the services manager this msg shows up:

The ServiceOnTest service on your Local Computer started and then stopped. Some services stop automatically if they have no work to do, for example, the performance Logs and the Alters service.

where ServiceOnTest is the service name ,

just to know if it matters: the startup type is automatically and it run for the local System


what should I do to make it work, I need it to insert to the database and more but first I need to know what wrong I did?

Urgent help is needed , please
Thanks

Recommended Answers

All 5 Replies

First step would be to log the error message to the event log so you know what went wrong.
Does this code work from a standard app ?

I guess I guess it may fail because SQL Service didn't start yet.. Follow Jerry advice for better error understading..

it may fail because SQL Service didn't start yet..

Is there a way to make the SQL service run before the windows log on ?, if yes, what should I do besides making the SQL service starts up Automatic,

thanks

I didn't work with services before I don't know if there's a way to check the service running or not! but I've dummy solution is to try connecting to sql server if it catch an error wait for period of time then try connecting if successed call the method which do some operations with SQL.

Does it insert the record once?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.