Try it yourself with our free Sql Formatter tool — runs entirely in your browser, no signup needed.

How to Format SQL queries in C#

How to Format SQL Queries in C#

Formatting SQL queries in C# is crucial for ensuring the readability, maintainability, and performance of your database interactions. A well-formatted query can make a significant difference in debugging, optimizing, and understanding the behavior of your application. In this guide, we will walk you through the process of formatting SQL queries in C#, covering the most common use case, handling edge cases, common mistakes, and performance tips.

Quick Example

Here is a minimal example of how to format a SQL query in C# using the System.Data.SqlClient namespace:

using System.Data.SqlClient;

public class SqlFormatter
{
    public static string FormatQuery(string query)
    {
        using (var connection = new SqlConnection("YourConnectionString"))
        {
            connection.Open();
            var command = new SqlCommand(query, connection);
            return command.CommandText;
        }
    }
}

// Usage:
string query = "SELECT * FROM customers WHERE country='USA'";
string formattedQuery = SqlFormatter.FormatQuery(query);
Console.WriteLine(formattedQuery);

This example uses the SqlCommand class to execute the query and retrieve the formatted query text.

Step-by-Step Breakdown

Let's break down the code line by line:

  1. using System.Data.SqlClient; - Import the System.Data.SqlClient namespace to access the SqlConnection and SqlCommand classes.
  2. public class SqlFormatter - Define a new class SqlFormatter to encapsulate the formatting logic.
  3. public static string FormatQuery(string query) - Define a static method FormatQuery that takes a SQL query string as input and returns the formatted query string.
  4. using (var connection = new SqlConnection("YourConnectionString")) - Create a new SqlConnection object with a valid connection string. The using statement ensures the connection is disposed of properly.
  5. connection.Open() - Open the database connection.
  6. var command = new SqlCommand(query, connection) - Create a new SqlCommand object with the input query and the opened connection.
  7. return command.CommandText - Return the formatted query text, which is stored in the CommandText property of the SqlCommand object.

Handling Edge Cases

Empty/Null Input

To handle empty or null input, you can add a simple null check and return an empty string or throw an exception:

public static string FormatQuery(string query)
{
    if (string.IsNullOrEmpty(query))
    {
        return string.Empty; // or throw new ArgumentException("Query cannot be null or empty");
    }
    // ...
}

Invalid Input

To handle invalid input, you can use a try-catch block to catch SqlException instances:

public static string FormatQuery(string query)
{
    try
    {
        // ...
    }
    catch (SqlException ex)
    {
        throw new ArgumentException("Invalid query: " + ex.Message);
    }
}

Large Input

To handle large input, you can use the SqlCommand class's CommandTimeout property to set a timeout value:

public static string FormatQuery(string query)
{
    using (var connection = new SqlConnection("YourConnectionString"))
    {
        connection.Open();
        var command = new SqlCommand(query, connection);
        command.CommandTimeout = 300; // 5 minutes
        // ...
    }
}

Unicode/Special Characters

To handle Unicode and special characters, you can use the SqlCommand class's Parameters property to parameterize the query:

public static string FormatQuery(string query, SqlParameter[] parameters)
{
    using (var connection = new SqlConnection("YourConnectionString"))
    {
        connection.Open();
        var command = new SqlCommand(query, connection);
        command.Parameters.AddRange(parameters);
        // ...
    }
}

Common Mistakes

1. Not disposing of the connection

Wrong:

var connection = new SqlConnection("YourConnectionString");
connection.Open();
// ...

Correct:

using (var connection = new SqlConnection("YourConnectionString"))
{
    connection.Open();
    // ...
}

2. Not handling exceptions

Wrong:

public static string FormatQuery(string query)
{
    // ...
}

Correct:

public static string FormatQuery(string query)
{
    try
    {
        // ...
    }
    catch (SqlException ex)
    {
        throw new ArgumentException("Invalid query: " + ex.Message);
    }
}

3. Not parameterizing the query

Wrong:

public static string FormatQuery(string query)
{
    using (var connection = new SqlConnection("YourConnectionString"))
    {
        connection.Open();
        var command = new SqlCommand(query, connection);
        // ...
    }
}

Correct:

public static string FormatQuery(string query, SqlParameter[] parameters)
{
    using (var connection = new SqlConnection("YourConnectionString"))
    {
        connection.Open();
        var command = new SqlCommand(query, connection);
        command.Parameters.AddRange(parameters);
        // ...
    }
}

Performance Tips

1. Use parameterized queries

Using parameterized queries can improve performance by reducing the overhead of parsing and compiling the query.

2. Use connection pooling

Connection pooling can improve performance by reducing the overhead of opening and closing connections.

3. Optimize query execution

Optimizing query execution can improve performance by reducing the time it takes to execute the query.

FAQ

Q: What is the purpose of the FormatQuery method?

A: The FormatQuery method formats a SQL query by executing it and retrieving the formatted query text.

Q: How do I handle invalid input?

A: You can use a try-catch block to catch SqlException instances and throw an exception with a meaningful error message.

Q: How do I handle large input?

A: You can use the SqlCommand class's CommandTimeout property to set a timeout value.

Q: How do I handle Unicode and special characters?

A: You can use the SqlCommand class's Parameters property to parameterize the query.

Q: What is the benefit of using parameterized queries?

A: Using parameterized queries can improve performance by reducing the overhead of parsing and compiling the query.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp