Building a Dynamic Query Executor for SQL Server and Oracle in ASP.NET Web Forms
In modern web applications, there are often scenarios where users need the flexibility to run dynamic queries against a database directly from a web interface. This is especially useful for admin tools, reporting dashboards, or troubleshooting interfaces where access to the database needs to be quick and easy. Today, we'll walk through building an ASP.NET Web Forms page that allows users to run queries against either SQL Server or Oracle databases with a flexible, user-friendly interface.
In this blog post, we'll cover the following:
- Why a Dynamic Query Executor is Useful
- Building the ASP.NET Web Forms Page
- Supporting Different Types of Queries (SELECT, INSERT, UPDATE, DELETE, Procedures, Views)
- Handling SQL Server and Oracle Connections
- Securing the Application with Parameterized Queries
- Testing and Running the Application
Let’s dive into the solution!
Why a Dynamic Query Executor is Useful
A query execution interface that supports multiple databases and types of queries can be incredibly beneficial for:
- Administrators: Quickly run maintenance queries without needing to open a full-fledged database client.
- Developers: Test queries or stored procedures directly from the application.
- Reporting and Analysis: Enable dynamic reporting by executing queries on-demand.
- Troubleshooting: Diagnose issues with the database directly from the web application.
For our solution, we’ll build a C# ASP.NET Web Forms page where users can input the connection details, choose the type of database (SQL Server or Oracle), and execute any SQL query they like.
Building the ASP.NET Web Forms Page
First, we’ll create an input form that asks users for the following information:
- Database Type: Either SQL Server or Oracle.
- Server Name: The address of the database server.
- Database Name (or SID for Oracle): The database name or the SID for Oracle.
- Username and Password: For connecting to the database.
- Port: An optional field (especially useful for Oracle).
- SQL Query: A multiline input box where users can enter their queries.
Here’s what the UI looks like in Default.aspx:
html<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="QueryExecutorApp._Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>SQL/Oracle Query Executor</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Execute SQL/Oracle Query</h2>
<table>
<tr>
<td>Select Database:</td>
<td>
<asp:RadioButtonList ID="rblDatabaseType" runat="server">
<asp:ListItem Text="SQL Server" Value="SQLServer"></asp:ListItem>
<asp:ListItem Text="Oracle" Value="Oracle"></asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
<tr>
<td>Server Name:</td>
<td><asp:TextBox ID="txtServer" runat="server" Width="400px"></asp:TextBox></td>
</tr>
<tr>
<td>Database Name (or SID for Oracle):</td>
<td><asp:TextBox ID="txtDatabase" runat="server" Width="400px"></asp:TextBox></td>
</tr>
<tr>
<td>User Name:</td>
<td><asp:TextBox ID="txtUsername" runat="server" Width="400px"></asp:TextBox></td>
</tr>
<tr>
<td>Password:</td>
<td><asp:TextBox ID="txtPassword" runat="server" TextMode="Password" Width="400px"></asp:TextBox></td>
</tr>
<tr>
<td>Port:</td>
<td><asp:TextBox ID="txtPort" runat="server" Width="400px"></asp:TextBox></td>
</tr>
<tr>
<td>Query:</td>
<td><asp:TextBox ID="txtQuery" runat="server" TextMode="MultiLine" Rows="5" Width="400px"></asp:TextBox></td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="btnExecute" runat="server" Text="Execute Query" OnClick="btnExecute_Click" /></td>
</tr>
</table>
<asp:Label ID="lblMessage" runat="server" ForeColor="Red" />
<br />
<asp:GridView ID="gvResults" runat="server" AutoGenerateColumns="true" Visible="false"></asp:GridView>
</div>
</form>
</body>
</html>
This layout allows the user to select the database type, enter connection details, and execute a query. If the query is a SELECT
statement, the results are displayed in a GridView
; for other queries (like INSERT
, UPDATE
, DELETE
), a message showing the affected rows is displayed.
Supporting Different Types of Queries (SELECT, INSERT, UPDATE, DELETE, Procedures, Views)
To support multiple types of queries, the backend must be dynamic enough to handle:
- SELECT Queries: Display results in a grid.
- INSERT/UPDATE/DELETE Queries: Show the number of rows affected.
- Stored Procedures: Execute them by recognizing the command type.
We also allow execution of Oracle-specific queries by providing fields for Oracle connection strings (like SID and port). We’ll handle the logic based on the selected database type.
Handling SQL Server and Oracle Connections
In the Default.aspx.cs code-behind file, we build connection strings dynamically based on user input. We use Oracle.ManagedDataAccess for Oracle and System.Data.SqlClient for SQL Server.
Here’s a snippet to build connection strings dynamically:
csharp// Build Oracle connection string
private string BuildOracleConnectionString(string server, string sid, string username, string password, string port)
{
return $"Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST={server})(PORT={port})))(CONNECT_DATA=(SID={sid})));User Id={username};Password={password};";
}
// Build SQL Server connection string
private string BuildSqlServerConnectionString(string server, string database, string username, string password)
{
return $"Server={server};Database={database};User Id={username};Password={password};";
}
Securing the Application with Parameterized Queries
Running dynamic queries can expose the system to SQL injection attacks, especially when accepting queries from user input. To secure the application, it’s crucial to use parameterized queries wherever possible.
For example, for an UPDATE
query:
csharpSqlCommand cmd = new SqlCommand("UPDATE Products SET Price = @Price WHERE ProductID = @ProductID", conn);
cmd.Parameters.AddWithValue("@Price", price);
cmd.Parameters.AddWithValue("@ProductID", productId);
This ensures that user input is treated as a parameter, not as part of the SQL statement, making the application more secure.
Error Handling and Testing the Application
We use try-catch blocks to catch any exceptions and display user-friendly error messages. The application should handle issues like incorrect connection details, invalid queries, or database timeouts gracefully.
csharptry
{
if (dbType == "Oracle")
{
string oracleConnectionString = BuildOracleConnectionString(server, database, username, password, port);
ExecuteOracleQuery(oracleConnectionString, query);
}
else
{
string sqlServerConnectionString = BuildSqlServerConnectionString(server, database, username, password);
ExecuteSqlServerQuery(sqlServerConnectionString, query);
}
}
catch (Exception ex)
{
lblMessage.Text = "Error: " + ex.Message;
}
Running the Application
Once the application is set up, users can access the page and:
- Select the database type (SQL Server or Oracle).
- Enter connection details (server name, database name or SID, username, password, port).
- Enter the query they want to execute.
- Click "Execute Query" and see the results.
For SELECT
queries, results are displayed in a grid view. For INSERT
, UPDATE
, and DELETE
operations, the number of rows affected is shown.
Conclusion
We’ve built a flexible, dynamic query execution tool in ASP.NET Web Forms that works with both SQL Server and Oracle databases. It can handle different types of queries, such as SELECT
, INSERT
, UPDATE
, and even stored procedures. Additionally, the tool uses best practices like parameterized queries to ensure security and prevent SQL injection.
This dynamic query executor can be expanded further by adding features like saved query history, result export, and more complex user roles for query permissions.
Comments
Post a Comment
Provide your valuable feedback, we would love to hear from you!! Follow our WhatsApp Channel at
https://whatsapp.com/channel/0029VaKapP65a23urLOUs40y