찾다
데이터 베이스MySQL 튜토리얼Access数据库多条数据Insert

Access数据库多条数据Insert

Jun 07, 2016 pm 04:23 PM
accessinsert데이터데이터 베이스

由于在此之前我没有用过Access数据库的,当需要想数据库中插入多条数据时,我们不妨先按照sql server的做法:insert into tablename(column1,column2) values (a,b),(c,d),(e,f)。于是按照这个思路,我的第一个方案出来了。 尝试一: The Demo: StringBuild

      由于在此之前我没有用过Access数据库的,当需要想数据库中插入多条数据时,,我们不妨先按照sql server的做法:“insert into tablename(column1,column2) values (a,b),(c,d),(e,f)”。于是按照这个思路,我的第一个方案出来了。

尝试一:

The Demo:

StringBuilder BuiList = new StringBuilder(string.Format("({0},0)", UserID)); foreach (RepeaterItem item in Rpt_AdminRole.Items) { if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem) { HtmlInputCheckBox cbRole = item.FindControl("cb_Role") as HtmlInputCheckBox; if (cbRole.Checked) { BuiList.Append(",("); BuiList.Append(UserID); BuiList.Append(","); BuiList.Append(cbRole.Value); BuiList.Append(")"); } } }

The Dal:

/// /// 添加Role关系 /// /// 角色关系 eg: "(1,1),(1,2)" /// public static int InsertRoleContact(string roleContact) { string sql = "insert into Sky_Admin_Role(AdminID,RoleID) values "+roleContact; return Common.OleDbHelper.ExecuteNonQuery(CommandType.Text, sql, null); }

exec下就会出现这样的错误:SQL 语句的结束位置缺少分号 (;)。

      Access对sql的支持果然是大大精简,到此尝试一失败!, 很快在我有另外idea。sql server 多表查询对select table 的支持!我可以直接传一个DataTable到sql语句中,说干就干! 

尝试二

The Demo : 获取DataTable

public DataTable GetInsertSQL(Repeater rep,string controlID) { DataTable data = new DataTable(); data.Columns.Add("AdminID"); data.Columns.Add("RoleID"); foreach (RepeaterItem item in rep.Items) { if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem) { HtmlInputCheckBox cb = item.FindControl(controlID) as HtmlInputCheckBox; if (cb.Checked) { DataRow row = data.NewRow(); row.ItemArray = new object[] { UserID, cb.Value}; data.Rows.Add(row); } } } return data; }

The Dal:

public static int InsertRoleContact(DataTable dt) { string sql = "insert into Sky_Admin_Role(AdminID,RoleID) select * from @Data"; OleDbParameter[] param = new OleDbParameter[] { new OleDbParameter("@Data",?){Value =dt} }; return Common.OleDbHelper.ExecuteNonQuery(CommandType.Text, sql, param); }

     当代码到这里我就知道此方法行不通,因为OledbType中没有对应的table类型,如果是SQL server由于支持xml可以设置为 SqlDbType.Xml类型来传递DataTable数据,由于sql本事对xml的支持 ,可以用sql基于xml的查询,本文主要讨论Access,此处暂不讨论了!尝试二宣布失败!。接下来我又想到了零时表,Access是不是也支持零时表的查询呢?

尝试三

The Demo: 取出我想要的数据格式 (1,2,3)

public string GetInserCollection(Repeater rep, string controlID) { StringBuilder buiCollecton = new StringBuilder(""); buiCollecton.Append("(0"); foreach (RepeaterItem item in rep.Items) { if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem) { HtmlInputCheckBox cb = item.FindControl(controlID) as HtmlInputCheckBox; if (cb.Checked) { buiCollecton.Append(string.Format(",{0}", cb.Value)); } } } buiCollecton.Append(")"); return buiCollecton.ToString(); }


The Dal :

public static int InsertRoleContact(int UserID,string RoleCollection)
        {
            StringBuilder BuiSQL = new StringBuilder("");
            BuiSQL.Append("declare @SkyContact table(userID int,roleID int);");
            BuiSQL.Append("insert into @SkyContact values select " + UserID + ",R_ID from Sky_Role;");
            BuiSQL.Append(string.Format("insert into Sky_Admin_Role values (select * from @SkyContact where roleID in {0})",RoleCollection));
            return Common.OleDbHelper.ExecuteNonQuery(CommandType.Text, BuiSQL.ToString(), null);
        }

      这里模仿SQL Server中定义一个零时表,然后向其中插入尽可能全的数据,然后在基于零时表查询出想要的数据放入到我想要的数据中执行!exec下结果又出问错了!此处抛出这样的错误:无效的 SQL语句;期待 'DELETE'、'INSERT'、'PROCEDURE'、'SELECT'、或 'UPDATE'。其实会出错完全可以想想的到,毕竟Access中连insert into table values (1,2),(1,3) 这样的语句都不支持。此时尝试三也不得不宣告失败!尝试了这么多,我不得不使用早就准备用的方法 多条insert一起执行。

尝试四

The Demo: 先获取我想要的数据形式 :1,2,3 此处略。看sql:

public static int InsertRoleContact2(int UserID, string RoleCollection) { string[] arr = RoleCollection.Split(','); StringBuilder BuilSQL = new StringBuilder(""); foreach (string item in arr) { BuilSQL.Append( string.Format("insert into Sky_Admin_Role(AdminID,RoleID) values ({0},{1});",UserID,Convert.ToInt32(item))); } return Common.OleDbHelper.ExecuteNonQuery(CommandType.Text, BuilSQL.ToString(), null); }
성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
MySQL Blob : 한계가 있습니까?MySQL Blob : 한계가 있습니까?May 08, 2025 am 12:22 AM

mysqlblobshavelimits : tinyblob (255bodes), blob (65,535 bytes), mediumblob (16,777,215 bctes), andlongblob (4,294,967,295 Bytes) .tousebl obseffectical : 1) 고려 사항을 고려합니다

MySQL : 사용자 생성을 자동화하는 가장 좋은 도구는 무엇입니까?MySQL : 사용자 생성을 자동화하는 가장 좋은 도구는 무엇입니까?May 08, 2025 am 12:22 AM

MySQL에서 사용자 생성을 자동화하기위한 최고의 도구 및 기술은 다음과 같습니다. 1. MySQLworkBench, 중소형 환경에 적합하고 사용하기 쉽지만 자원 소비가 높습니다. 2. 다중 서버 환경에 적합한 Ansible, 간단하지만 가파른 학습 곡선; 3. 사용자 정의 파이썬 스크립트, 유연하지만 스크립트 보안을 보장해야합니다. 4. 꼭두각시와 요리사는 대규모 환경에 적합하며 복잡하지만 확장 가능합니다. 선택할 때 척도, 학습 곡선 및 통합 요구를 고려해야합니다.

MySQL : 블로브 내부를 검색 할 수 있습니까?MySQL : 블로브 내부를 검색 할 수 있습니까?May 08, 2025 am 12:20 AM

예, youcansearchinsideablobinmysqlusingspecifictechniques.1) converttheblobtoautf-8stringwithConvertFunctionandSearchusing

MySQL 문자열 데이터 유형 : 포괄적 인 가이드MySQL 문자열 데이터 유형 : 포괄적 인 가이드May 08, 2025 am 12:14 AM

mysqloffersvariousStringDatatatypes : 1) charfixed-lengthstrings, 이상적인 원인이 길이의 길이가 길이 스트링스, 적합한 포르 플리드 슬리 키나 이름; 3) TextTypesforlargerText, goodforblogpostsbutcactperformance;

MySQL Blobs 마스터 링 : 단계별 자습서MySQL Blobs 마스터 링 : 단계별 자습서May 08, 2025 am 12:01 AM

TomasterMySQLBLOBs,followthesesteps:1)ChoosetheappropriateBLOBtype(TINYBLOB,BLOB,MEDIUMBLOB,LONGBLOB)basedondatasize.2)InsertdatausingLOAD_FILEforefficiency.3)Storefilereferencesinsteadoffilestoimproveperformance.4)UseDUMPFILEtoretrieveandsaveBLOBsco

MySQL의 Blob Data Type : 개발자를위한 상세한 개요MySQL의 Blob Data Type : 개발자를위한 상세한 개요May 07, 2025 pm 05:41 PM

blobdatatypesinmysqlareusedforvoringlargebinarydatalikeimagesoraudio.1) useblobtypes (tinyblobtolongblob) 기반 론다 타지 세인. 2) StoreBlobsin perplate petooptimize 성능.

명령 줄에서 MySQL에 사용자를 추가하는 방법명령 줄에서 MySQL에 사용자를 추가하는 방법May 07, 2025 pm 05:01 PM

toadduserstomysqlfromthecommandline, loginasroot, whenUseCreateUser'Username '@'host'IdentifiedBy'Password '; toCreateAwUser.grantPerMissionswithGrantAllilegesOndatabase

MySQL의 다른 문자열 데이터 유형은 무엇입니까? 자세한 개요MySQL의 다른 문자열 데이터 유형은 무엇입니까? 자세한 개요May 07, 2025 pm 03:33 PM

mysqlofferSeightStringDatatatypes : char, varchar, binary, varbinary, blob, text, enum and set.1) charisfix-length, 2) varcharisvariable-length, 효율적 인 datalikenames.3) binaryandvarbinary-binary Binary Binary Binary Binary Binary Binary Binary-Binary

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.