Home Database Mysql Tutorial Access数据库多条数据Insert

Access数据库多条数据Insert

Jun 07, 2016 pm 04:23 PM
access insert data database

由于在此之前我没有用过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); }
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1234
24
How to configure zend for apache How to configure zend for apache Apr 13, 2025 pm 12:57 PM

How to configure Zend in Apache? The steps to configure Zend Framework in an Apache Web Server are as follows: Install Zend Framework and extract it into the Web Server directory. Create a .htaccess file. Create the Zend application directory and add the index.php file. Configure the Zend application (application.ini). Restart the Apache Web server.

Oracle's Role in the Business World Oracle's Role in the Business World Apr 23, 2025 am 12:01 AM

Oracle is not only a database company, but also a leader in cloud computing and ERP systems. 1. Oracle provides comprehensive solutions from database to cloud services and ERP systems. 2. OracleCloud challenges AWS and Azure, providing IaaS, PaaS and SaaS services. 3. Oracle's ERP systems such as E-BusinessSuite and FusionApplications help enterprises optimize operations.

MySQL vs. Other Databases: Comparing the Options MySQL vs. Other Databases: Comparing the Options Apr 15, 2025 am 12:08 AM

MySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.

Using Dicr/Yii2-Google to integrate Google API in YII2 Using Dicr/Yii2-Google to integrate Google API in YII2 Apr 18, 2025 am 11:54 AM

VprocesserazrabotkiveB-enclosed, Мнепришлостольностьсясзадачейтерациигооглапидляпапакробоглесхетсigootrive. LEAVALLYSUMBALLANCEFRIABLANCEFAUMDOPTOMATIFICATION, ČtookazaLovnetakProsto, Kakaožidal.Posenesko

Nginx performance monitoring and troubleshooting tools Nginx performance monitoring and troubleshooting tools Apr 13, 2025 pm 10:00 PM

Nginx performance monitoring and troubleshooting are mainly carried out through the following steps: 1. Use nginx-V to view version information, and enable the stub_status module to monitor the number of active connections, requests and cache hit rate; 2. Use top command to monitor system resource occupation, iostat and vmstat monitor disk I/O and memory usage respectively; 3. Use tcpdump to capture packets to analyze network traffic and troubleshoot network connection problems; 4. Properly configure the number of worker processes to avoid insufficient concurrent processing capabilities or excessive process context switching overhead; 5. Correctly configure Nginx cache to avoid improper cache size settings; 6. By analyzing Nginx logs, such as using awk and grep commands or ELK

MySQL: Structured Data and Relational Databases MySQL: Structured Data and Relational Databases Apr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

What is apache server? What is apache server for? What is apache server? What is apache server for? Apr 13, 2025 am 11:57 AM

Apache server is a powerful web server software that acts as a bridge between browsers and website servers. 1. It handles HTTP requests and returns web page content based on requests; 2. Modular design allows extended functions, such as support for SSL encryption and dynamic web pages; 3. Configuration files (such as virtual host configurations) need to be carefully set to avoid security vulnerabilities, and optimize performance parameters, such as thread count and timeout time, in order to build high-performance and secure web applications.

How to solve nginx current limit How to solve nginx current limit Apr 14, 2025 pm 12:06 PM

The Nginx current limit problem can be solved by: use ngx_http_limit_req_module to limit the number of requests; use ngx_http_limit_conn_module to limit the number of connections; use third-party modules (ngx_http_limit_connections_module, ngx_http_limit_rate_module, ngx_http_access_module) to implement more current limit policies; use cloud services (Cloudflare, Google Cloud Rate Limiting, AWS WAF) to DD

See all articles