ExecuteNonQuery是否有其他替代命令?

时间:2019-04-25 14:45:53

标签: c# sql-server

我正在使用c#在医院管理信息系统上进行项目,并希望从c#将数据插入SQL Server,但是ExecuteNonQuery命令不起作用。该命令是否还有其他替代方法?

connection.Open();
command = new SqlCommand(sql, connection);
command.CommandType = CommandType.Text;
int i = command.ExecuteNonQuery();

command.Dispose();
connection.Close();

1 个答案:

答案 0 :(得分:1)

这是一个简单的代码,希望对您有所帮助。

try
{
    string connectionStringMS = WebConfigurationManager.ConnectionStrings["Your Connection String Name"].ConnectionString; // WebConfig
    using (SqlConnection conn = new SqlConnection(connectionStringMS)) 
    using (SqlCommand nonqueryCommand = conn.CreateCommand())
    {
        conn.Open();

        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.AppendLine(" INSERT INTO customer ");
        sqlBuilder.AppendLine(" (firstName, lastname) ");
        sqlBuilder.AppendLine(" VALUES ");
        sqlBuilder.AppendLine(" (@firstName, @lastname)");

        nonqueryCommand.Parameters.Add(new SqlParameter("@firstName", SqlDbType.VarChar, 50)).Value = "Brad";
        nonqueryCommand.Parameters.Add(new SqlParameter("@lastname", SqlDbType.VarChar, 50)).Value = "Test";

        nonqueryCommand.CommandText = sqlBuilder.ToString();

       nonqueryCommand.ExecuteNonQuery();
   }   
}
catch (Exception ex)
{
    ...
}

此致