Click here to Skip to main content
15,894,017 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
try
           {
               string connectionString =
                   "server=((localdb)-MSSQLLocalDB);" +
                   "initial catalog=Employee;";

               using (SqlConnection conn =
                   new SqlConnection(connectionString))
               {
                   conn.Open();
                   using (SqlCommand cmd =
                       new SqlCommand("INSERT INTO Employee VALUES(" +
                           "@EmpId, @EmpName, @EmpAddress,@EmpCode,@EmpDesig)", conn))
                   {
                       cmd.Parameters.AddWithValue("@EmpId", 5);
                       cmd.Parameters.AddWithValue("@EmpName", "Amal Hashim");
                       cmd.Parameters.AddWithValue("@EmpAddress", "Bangalore");
                       cmd.Parameters.AddWithValue("@EmpCode", 007);
                       cmd.Parameters.AddWithValue("@EmpDesig", "Manager");

                       int rows = cmd.ExecuteNonQuery();
                       Console.WriteLine("you are here");

                       //rows number of record got inserted
                   }
               }
           }
           catch (SqlException ex)
           {
               Console.WriteLine("Try block is failed");
           }


What I have tried:

Try to add a data in database using console application.
Posted
Updated 3-May-16 19:43pm
Comments
Raje_ 4-May-16 1:36am    
What type of error you are getting??? Did you debug? Is your sql connection open?
Richard MacCutchan 4-May-16 2:55am    
You are not checking the result of your call to cmd.ExecuteNonQuery() so any errors will be ignored. You must check the result values from system calls to check whether your request was successful or not.

1 solution

I think your connection string is not written properly.

It should be :
<br />
connetionString="Data Source=YourServerName;<br />
Initial Catalog=YourDatabaseName; User ID=UserName;Password=Password"


Incase you are using Windows Authentication you just have to remove User Id and Password and add Integrated Security=True

You can go through below link for more detail :

C# SQL Server Connection[^]
 
Share this answer
 
Comments
@j@y123 4-May-16 2:52am    
not working still data not added in the database

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