■ 복수 INSERT문을 실행하는 방법을 보여준다.
▶ SQL Server 테이블 (SQL)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
CREATE TABLE dbo.Student ( ID INT NOT NULL ,Name NVARCHAR(50) NOT NULL ,CreateTime DATETIME NOT NULL CONSTRAINT PKStudent PRIMARY KEY CLUSTERED (ID ASC) WITH ( PAD_INDEX = OFF ,STATISTICS_NORECOMPUTE = OFF ,IGNORE_DUP_KEY = OFF ,ALLOW_ROW_LOCKS = ON ,ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY] ) ON [PRIMARY] GO |
▶ 예제 코드 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
using System; using System.Data.SqlClient; using Dapper; ... /// <summary> /// 학생 /// </summary> public class Student { /// <summary> /// ID /// </summary> public int ID { get; set; } /// <summary> /// 성명 /// </summary> public string Name { get; set; } /// <summary> /// 생성 일시 /// </summary> public DateTime CreateTime { get; set; } } ... string connectionString = "Data Source=127.0.0.1;Initial Catalog=TestDB;UID=sa;PWD=1234;Timeout=30"; using(SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); List<Student> studentList = new List<Student>(); for(int i = 1; i < 101; i++) { studentList.Add(new Student { ID = i, Name = "학생" + i.ToString(), CreateTime = DateTime.Now }); } SqlTransaction transaction = connection.BeginTransaction(); try { connection.Execute("INSERT dbo.Student (ID, Name, CreateTime) VALUES (@ID, @Name, @CreateTime)", studentList, transaction); transaction.Commit(); } catch { transaction.Rollback(); } } |