.NET Framework 作为命令执行SQL语句

示例

//使用Windows身份验证。将Trusted_Connection参数替换为
//用户ID = ...;密码= ...; 而是使用SQL Server身份验证。你可以
// 想要找到适合您服务器的连接字符串。
string connectionString = @"Server=myServer\myInstance;Database=myDataBase;Trusted_Connection=True;"

string sql = "INSERT INTO myTable (myDateTimeField, myIntField) " +
    "VALUES (@someDateTime, @someInt);";

// 大多数ADO.NET对象都是一次性的,因此需要using关键字。
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(sql, connection))
{
    // 使用参数而不是字符串连接来添加用户提供的
    //值,以避免SQL注入和格式设置问题。明确提供数据类型。

    //System.Data.SqlDbType是一个枚举。见注1
    command.Parameters.Add("@someDateTime", SqlDbType.DateTime).Value = myDateTimeVariable;
    command.Parameters.Add("@someInt", SqlDbType.Int).Value = myInt32Variable;

    //执行SQL语句。改用ExecuteScalar和ExecuteReader
    // 用于返回结果的查询(或者一次查看更具体的示例)
    // 这些已添加)。

    connection.Open();
    command.ExecuteNonQuery();
}

注意1:有关MSFT SQL Server特定版本的信息,请参见SqlDbType枚举。

注意2:有关MySQL特定版本的信息,请参见MySqlDbType枚举。