Frame the SQL Query using String Function Format()

The main idea behind this FAQ is to frame our SQL Query using String Format Function. I think this is one of the best way to frame the SQL Query that i found. *** This code introduces SQL injection attacks and should not be used. ***

The string.Format method is a static method that receives a string that specifies where the following arguments should be inserted, and these are called substitutions.

In source code we need to use to frame the SQL Query
public bool SaveData(string firstName, string lastName)
    {
         
String connectionString = ConfigurationManager.ConnectionStrings["TESTDB"].ConnectionString;
        
bool result = false;
        
using (SqlConnection connection = new SqlConnection(connectionString))
        {
          
SqlCommand cmd = new SqlCommand();
            cmd.
Connection = connection;
             cmd.
CommandText = String.Format("insert into Test_DB.dbo.PersonName(FirstName,LastName) values ('{0}','{1}')", firstName, lastName);
             cmd.
CommandType = CommandType.Text;
            connection.
Open();
            
int count = cmd.ExecuteNonQuery();
            
if (count > 0)
            {
                result =
true;
            }
            
else
            {
                result =
false;
            }
        }
         
return result;
    }

Like this we can frame the Update and Delete Statements also.  Please refer this link for more about the String Format function.

Comments

Popular posts from this blog

Exporting to excel from a custom class object using C#.NET

Why Dispose() is preferred than Finalize() for Un-Managed Resources in .NET?

How to apply watermark to the textbox and dropdownlist?