Home HTML5 CSS JavaScript C ++ Python Java PHP Digital Marketing .Net Django SQL Canvas

ASP.NET ADO(ActiveX Data Objects for .NET) Add:


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:

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.


Advertisement
Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java