在C#中向Azure SQL数据库插入数据,可以使用ADO.NET库中的SqlClient类。以下是一个示例代码:

using System.Data.SqlClient;

// 连接字符串,替换为自己的数据库连接信息
string connectionString = "Server=tcp:<your-server-name>.database.windows.net,1433;Initial Catalog=<your-db-name>;Persist Security Info=False;User ID=<your-username>;Password=<your-password>;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";

// SQL插入语句
string sql = "INSERT INTO <your-table-name> (column1, column2, column3) VALUES (@value1, @value2, @value3)";

// 创建连接对象
SqlConnection connection = new SqlConnection(connectionString);

// 创建命令对象
SqlCommand command = new SqlCommand(sql, connection);

// 添加参数
command.Parameters.AddWithValue("@value1", "value1");
command.Parameters.AddWithValue("@value2", "value2");
command.Parameters.AddWithValue("@value3", "value3");

try
{
    // 打开连接
    connection.Open();

    // 执行插入操作
    int rowsAffected = command.ExecuteNonQuery();

    // 输出影响的行数
    Console.WriteLine("Rows affected: " + rowsAffected);
}
catch (Exception ex)
{
    // 处理异常
    Console.WriteLine(ex.Message);
}
finally
{
    // 关闭连接
    connection.Close();
}

在示例代码中,需要将连接字符串替换为自己的数据库连接信息,同时将SQL语句中的表名和列名替换为实际的表名和列名。然后使用SqlCommand对象的Parameters属性添加参数,并执行ExecuteNonQuery方法来执行插入操作。最后关闭连接对象。

C#像Azure sql中插入数据

原文地址: https://www.cveoy.top/t/topic/ueH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录