ExecuteNonQuery에서 영향을 받는 행을 가져옵니다.
현재 C# 프로젝트를 진행하고 있으며, 동시에 선택을 하는 삽입 쿼리를 실행하고 있습니다.예를 들어 다음과 같습니다.
INSERT INTO table (SELECT * FROM table WHERE column=date)
이 쿼리 중에 몇 행이 삽입되었는지 확인할 수 있는 방법이 있습니까?
ExecuteNonQuery- 영향을 받는 행 수를 반환합니다.
SqlCommand comm;
// other codes
int numberOfRecords = comm.ExecuteNonQuery();
에서 질문에서 SQL을 실행하는 경우SqlCommand의 반환값을 확인합니다.ExecuteNonQuery얼마나 많은 기록이 영향을 받았는지 알 수 있을 겁니다
매뉴얼에서 다음 항목을 참조하십시오.
반환값
유형: 시스템.Int32
영향을 받는 행의 수.
접속 문자열에 스테이트먼트를 추가해야 합니다.다음은 예를 제시하겠습니다.
string const "Server=localhost; PORT=3306; Database=db; User id=root; password='';UseAffectedRows=True";
MySqlConnection con = new MySqlConnection(const);
con.Open();
MySqlCommand cmd = new MySqlCommand(con);
cmd.CommandText = "Update db set table = value where Column = value";
int numberOfRecords = cmd.ExecuteNonQuery();
다음 사항을 확인합니다.
UseAffectedRows=True
따라서 영향을 받는 행의 올바른 값을 반환합니다.
ExecuteNonQuery는 연결 속성에서 영향을 받는 행 사용을 설정한 경우에만 영향을 받는 행을 반환합니다. 그렇지 않은 경우(기본값) 일치하는 행을 반환합니다.
ExecuteNonQuery()의 대부분을 실행하고 모든 것을 한 번에 커밋하는 경우 "SELECT total_changes()"에서 반환값을 읽으면 연결 후 총 변경 수를 얻을 수 있습니다.
전체 변경 내용을 가져오는 함수:
public static long GetTotalChanges(SQLiteConnection m_dbConnection)
{
string sql = "SELECT total_changes();";
using (SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection))
{
using (SQLiteDataReader reader = command.ExecuteReader())
{
reader.Read();
return (long)reader[0];
}
}
}
다른 기능으로 사용합니다.
public static long MyBulkInserts()
{
using (SQLiteConnection m_dbConnection = new SQLiteConnection())
{
m_dbConnection.Open();
using (var cmd = new SQLiteCommand(m_dbConnection))
{
using (var transaction = m_dbConnection.BeginTransaction())
{
//loop of bulk inserts
{
cmd.ExecuteNonQuery();
}
transaction.Commit();
}
}
return GetTotalChanges(m_dbConnection);
}
}
ExecuteNonquery를 사용하여 이 작업을 수행하려는 것은 알지만 ExecutScalar를 사용하여 쿼리에서 OUTPUT 디렉티브를 사용하는 것은 어떻습니까?
삽입의 경우:
declare @resulttable
(
rowid int
)
insert yourtable
output inserted.rowid
into @resulttable
select *
from someothertable
select count(1) affectedrows
from @resulttable
또는 [Update]의 경우 변경된 행만 알고 싶은 경우
declare @resulttable
(
beforefield1 varchar(255),
afterfield1 varchar(255)
)
update tbl1
set field1 = replace(field1, 'oldstring', 'newstring')
output deleted.field1,
inserted.field1
into @resulttable
from someothertable
select count(1) affectedrows
from @resulttable
where beforefield1 != afterfield1;
언급URL : https://stackoverflow.com/questions/10059158/get-affected-rows-on-executenonquery
'programing' 카테고리의 다른 글
| Java Set의 순서 유지? (0) | 2022.12.24 |
|---|---|
| C에서 콘솔 화면을 지우려면 어떻게 해야 합니까? (0) | 2022.12.24 |
| 삽입처...모든 MySQL 열에 대해 선택 (0) | 2022.12.24 |
| 반환값과 Promise.resolve의 차이점은 무엇입니까? (0) | 2022.12.24 |
| 행잉 포인터와 메모리 누수의 차이 (0) | 2022.12.24 |