Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
Hello All,

I stuck up with google seach to find out what is the simple way to do this.

1) Run "SELECT ID,Name FROM Member WHERE ID=12" from C# code and export value of ID and Name into two separate variable (Int_Id, Str_Name).
2) Update a table for a value using some condition.
3) Delete a rows from table for some condition.
4) Insert one record into a table . same like executinn "INSERT INTO ...." query from C#.

Please guid me. I tried this from search result what google has provided to me.
but its a log way of using adaptot , command , reader , dataset.
Posted
Updated 25-Apr-11 2:39am
v2

Here goes, this is basically everything you want to know in terms of handling executing SQL on SqlServer using C#. Read through the comments and try to understand.

This example only has a select SQL, for other SQL like "DELETE, INSERT, CREATE TABLE, UPDATE" all you have to do is change the CommandText to whatever the SQL you want to execute and choose the appropriate method accordingly. :)
// This is your connection to your database
using (SqlConnection connection = new SqlConnection())
{
    connection.ConnectionString = "Put your connection string here";

    // This creates an object with which you can execute sql
    using (SqlCommand command = connection.CreateCommand())
    {
        command.CommandText = "SELECT COUNT(*) FROM TestTable WHERE TestId = @TestId";
        command.CommandType = CommandType.Text;
        // If the SQL you want to execute is a stored procedure, use the commented 2 lines below
        // instead of the 2 lines above.
        // command.CommandText = "SP_GetTestSubjectCount_Select";
        // command.CommandType = CommandType.StoredProcedure;

        // This is how you add a parameter to your sql command
        // This way you are protected against SQL injection attacks
        SqlParameter testIdParameter = command.CreateParameter();
        testIdParameter.ParameterName = "@TestId";
        testIdParameter.Value = "Some Value";
        command.Parameters.Add(testIdParameter);

        try
        {

            connection.Open();

            // This is the easiest way to iterate through the returned results with MULTIPLE rows
            // This way can ONLY be used for SELECT statements or SPs which returns results
            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                Console.WriteLine(reader.GetInt32(0));
            }

            // If your SQL returns just ONE VALUE you can use the code below
            int testObjectCount = (int)command.ExecuteScalar();

            // For DELETE, UPDATE, INSERT statements which does not return a resultset
            // instead they return the number of records affected
            // Use the code below for that instead of the above code
            int affectedRows = command.ExecuteNonQuery();

        }
        finally
        {
            try
            {
                if (connection.State == ConnectionState.Open)
                    connection.Close();
            }
            catch
            {
                // This catch block suppresses any errors occured while closing the connection
                // remove the try catch block if you want your application to know of this exception as well
            }
        }
    }
}


I know I am spoiling you with just giving you the code, but I am way bored at work today, so consider this as a good gesture :D Just for this time. Don't bite your nails, won't happen again :D

Hope this helps. Regards :)
 
Share this answer
 
Comments
Nish Nishant 25-Apr-11 9:01am    
Voted 5.
CodeHawkz 25-Apr-11 12:01pm    
Thnx :)
I suggest you Google SqlConnection and SqlCommand. You basically create a connection to the database with the first and use to execute the command on the server.
The method for selecting SqlCommand you want is ExecuteReader. For the remaining "CUD" operations you will need to use ExecuteNonQuery Don't forget to close the connection when done, and protect yourself from SQL Injection attacks.
This[^] should get you started.
 
Share this answer
 
v2
Comments
RDBurmon 21-Apr-11 15:32pm    
Good post .. Waiting for some other reply. to accept.
Prasanta_Prince 22-Apr-11 1:51am    
Good Solution.

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