本文介绍了Executescalar要求命令具有事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

目前我正在使用带有SQL Server 2014的asp.net

currently i m using asp.net with SQL Server 2014

while executing the below coding




string query = "INSERT INTO [Classes] ([Class],[NoOfSections],[DateCreated]," +
                "[LastModified]) output inserted.Id  VALUES ('" + classname + "' ,'" + noOfSections + "',getdate(),getdate())";
            SqlConnection con = CreateConnection();
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = query;
            cmd.Connection = con;
            SqlTransaction trans ;
            using (trans= con.BeginTransaction())
            {
                long classId = Convert.ToInt64(cmd.ExecuteScalar());
                //int? classId = (oclass as int);
                AddNewSections(classId, noOfSections);
                trans.Commit();
            }
            con.Close();




i m getting the below error




ExecuteScalar requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized.





我尝试过:



帮助我PLZ ..即时尝试使用事务获取插入的记录autoid。我怎样才能实现呢?



What I have tried:

help me plz.. i m trying to fetch the inserted records autoid using transactions. how can i achieve it?

推荐答案

trans= con.BeginTransaction();
cmd = new SqlCommand(query, con, tran);
long classid= Convert.toInt64(cmd.ExecuteNonQuery());
trans.Commit();







ExecuteScalar()用于查询(选择)只返回一个字段。

插入/更新使用ExecuteNonQuery()。




ExecuteScalar() is used for query ("select") that returns just one field.
to insert/update ExecuteNonQuery() is used.


string sql = "INSERT INTO MyTable (uName)  OUTPUT inserted.id VALUES ('abcd')";
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlTransaction trans = con.BeginTransaction())
        {
        using (SqlCommand cmd = new SqlCommand(sql, con, trans))
            {
            int x = (int)cmd.ExecuteScalar();
            Console.WriteLine(x);
            trans.Commit();
            }
        }
    }


这篇关于Executescalar要求命令具有事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 20:28