To add data to a database using ADO.NET in an ASP.NET application, you typically execute an INSERT SQL command. Here's a basic example demonstrating how to add data to a SQL Server database using ADO.NET:
Example
using System;
using System.Data.SqlClient;
namespace YourNamespace
{
public class YourClassName
{
public void AddData(string name, int age)
{
// Connection string to your database
string connectionString = "Data Source=YourServer;Initial Catalog=YourDatabase;User ID=YourUsername;Password=YourPassword";
// SQL query to insert data
string query = "INSERT INTO YourTable (Name, Age) VALUES (@Name, @Age)";
// Create a SqlConnection to connect to the database
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Create a SqlCommand to execute the query
using (SqlCommand command = new SqlCommand(query, connection))
{
// Add parameters to the command to prevent SQL injection
command.Parameters.AddWithValue("@Name", name);
command.Parameters.AddWithValue("@Age", age);
try
{
// Open the database connection
connection.Open();
// Execute the INSERT command
int rowsAffected = command.ExecuteNonQuery();
if (rowsAffected > 0)
{
Console.WriteLine("Data added successfully.");
}
else
{
Console.WriteLine("No rows were affected.");
}
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}
}
}
}
In this example:
AddData
that takes the name and age of the person to be added to the database.SqlConnection
to connect to the database using a connection string.SqlCommand
with the INSERT query and add parameters to it to prevent SQL injection.ExecuteNonQuery()
method of the SqlCommand
.You can call this AddData
method from your ASP.NET code-behind or controller to add data to the database. Make sure to replace placeholders like YourServer
, YourDatabase
, YourUsername
, YourPassword
, YourTable
with the actual values relevant to your database setup.