首页 数据库 mysql教程 Data Access FAQ (一)

Data Access FAQ (一)

Jun 07, 2016 pm 03:43 PM
access data faq

前些日子,写了ASP.NET Data Access的FAQ,现在贴出来和大家一起分享,希望对大家有帮助! 这里是第一部分: 打包下载 Table of Contents General How can I set the parameter values of ObjectDataSource in code-behind? Comparing DataSet and DataReader

前些日子,写了ASP.NET Data Access的FAQ,现在贴出来和大家一起分享,希望对大家有帮助! 这里是第一部分:

打包下载

Table of Contents

General

How can I set the parameter values of ObjectDataSource in code-behind?

Comparing DataSet and DataReader.

How to update the primary key in ObjectDataSource when used with GridView.

How to call a parameterized stored procedure via ADO.NET.

Why ObjectDataSource couldn’t find the type specified in TypeName property.

How to update all the changes in DataTable/DataSet.

How can I get the return value when calling stored procedure in typed DataSet?

What’s SQL injection? How to avoid that?

Why I can’t connect to my database and I also get the error ‘connection out of time’?

Failed to enable constraints in typed DataSet.

How to handle slow querying in a database.

How to select distinct rows in a DataTable.

LINQ

How can I implement a transaction in LINQ?

How can I use left join in LINQ.

What’s the difference between List and IQueryable?

How to implement ‘Like’ operation in LINQ just like in SQL script?

How to query a DataTable using LINQ?

 

 

General

How can I set the parameter values of ObjectDataSource in code-behind?

A: Suppose that you want to set the parameters in the Select method of ObjectDataSource. You can handle the Selecting event of ObjectDataSource to set the parameters. For example:

protected void ObjectDataSource1_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)

{

    e.InputParameters["accountID"] = 5;

}

Comparing DataSet and DataReader.

A: DataSet is a collection of DataTables and relations between the tables. It is used to hold tables with data, you can select data from tables or create views and access child rows. Also DataSet provides you with rich features like saving data to XML and loading data from XML. DataReader is an object that is used to iterate through a result set that was queried from a server and reads one row per move. If you want forward-only access to the results then DataReader is the best option because it is the most efficient method in this scenario.

Related link:

http://www.windowsitlibrary.com/Content/1205/06/files/Table3.html

How to update the primary key in ObjectDataSource when used with GridView.

A: If you need to update the primary key in Business Logic Layer (BLL), you need to specify DataKeyNames property in GridView control and OldValuesParameterFormatString property in ObjectDataSource control. For example:

asp:ObjectDataSource ID="ObjectDataSource1" runat="server"

            OldValuesParameterFormatString="original_{0}" SelectMethod="SelectDecs"

            TypeName="Job.Code.bll" UpdateMethod="UpdateDec">

            UpdateParameters>

                asp:Parameter Name="original_id" Type="Int32" />

                asp:Parameter Name="id" Type="Int32" />

                asp:Parameter Name="value" Type="Decimal" />

            UpdateParameters>

        asp:ObjectDataSource>

The signature of the update method in Business Logic Layer is:

[System.ComponentModel.DataObjectMethod(System.ComponentModel.DataObjectMethodType.Update, true)]

public void UpdateDec(int original_id, int id, decimal value)

How to call a parameterized stored procedure via ADO.NET.

A: When calling a parameterized stored procedure via ADO.NET, you need to set the CommandType property to ‘StoredProcedure’, and correctly set the Direction property when passing parameters into the command. The example below demonstrates how to call a parameterized stored procedure.

cmd.CommandType = CommandType.StoredProcedure;

 

SqlParameter id = cmd.Parameters.Add("@id", SqlDbType.Int, 4);

id.Direction = ParameterDirection.Input;

SqlParameter uName = cmd.Parameters.Add("@uName",SqlDbType.Char,20);

uName.Direction = ParameterDirection.Output;

SqlParameter ret = cmd.Parameters.Add("@Return_value",SqlDbType.Int,4);

ret.Direction = ParameterDirection.ReturnValue;

           

id.Value = 2;

conn.Open();

cmd.ExecuteNonQuery();

Response.Write("
OutPut Value:"
+ uName.Value);

Response.Write("
Return Value:"
+ ret.Value);

Why ObjectDataSource couldn’t find the type specified in TypeName property.

A: Please check your project’s references and ensure the source code or assembly that contains the type is in the right location. The type specified in TypeName property of ObjectDataSource should be in Bin, App_Code or GAC. If your type can’t be loaded from assemblies in the related directories, a runtime exception will be thrown.

P.S You can also use Fusion log viewer tool to see the binding failures.

Related link: http://blogs.msdn.com/suzcook/archive/2003/05/29/57120.aspx

How to update all the changes in DataTable/DataSet.

A: Usually,you can update all the changes in DataTable/DataSet to the database with the help of CommandBuilder object. A CommandBuilder object will help to generate all the changes in DataTable/DataSet to SQL statements which will be executed by the Command object.

To update all the changes to SQL Server, we can write the code as shown below:

da.Fill(ds, "tab1");

SqlCommandBuilder cb = new SqlCommandBuilder(da);

 

ds.Tables[0].Rows[0]["username"] = "Modified Name";

da.UpdateCommand = cb.GetUpdateCommand();

da.Update(ds); 

How can I get the return value when calling stored procedure in typed DataSet?

A: As we know, the stored procedure is called as a method of a typed DataSet. But when we return a value from a stored procedure, we can’t get it via the form of ‘(int)da.CallSP(xx,xx);’. If you want to get the return value from a stored procedure, you need to write a new method in the partial class of TableAdapters as shown below – the input parameter is the index of the method in the TableAdapter which can be easily seen in the designer of typed DataSet.

partial class UsersTableAdapter

{

     public object GetReturnValue(int commandIndex)

     {

         return this.CommandCollection[commandIndex].Parameters[0].Value;

     }

}

Then you can call this method to get the return value:

da.CallSP(xx, xx);

int returnValue = int.Parse(da.GetReturnValue(2).ToString());

What’s SQL injection? How to avoid that?

A: When you use a string query to build a SQL statement with input values from end-user, it is easy to have a SQL injection attack. For example, we have the following SQL statement to verify a user’s password:

sql = "select * from UserInfo where password='" + password + "'";

A malicious user can use the following input to bypass the password check:

password = "' or 1=1 --";

Even worse, some dangerous SQL commands such as “’; DROP TABLE …” might be executed.

To avoid SQL injection, we can use command parameters in SQL query – this will be efficient to validate the user. The single quotes will be filtered.

cmd = new SqlCommand("select * from UserInfo where password=@ password", conn);

SqlParameter pwd = cmd.Parameters.Add("@password", SqlDbType.Char, 20);

pwd.Direction = ParameterDirection.Input;

pwd.Value = "' or 1=1 --";

Why I can’t connect to my database and I also get the error ‘connection out of time’?

A: The time-out value of SqlConnection or SqlCommand object might be too small.

The default time out of SqlConnection is 15 seconds. You can set this time longer via these two ways.

·         Set the ConnectionTimeout property of SqlConnection object.

·         Set the Connect Timeout property in the connection string.

The default time out of the SqlCommand is 30 seconds. You can also set this time longer.

·         Set the CommandTimeout property of SqlCommand object.

Failed to enable constraints in typed DataSet.

A: The problem was caused by a discrepancy between the defined max size of a data column in your project's XSD and the size in database. The error is because one of the columns in the database is larger than the one in XSD / table adapter. You can try to update the table schema in XSD or modify the maximum size of a data column manually.

How to handle slow querying in a database.

A: There may be several possible causes, here are some general suggestions:

·         Is your table very large?  Is it possible to split it into several smaller tables?

·         If you don't use all the fields, you could just return the required fields when constructing your SQL statements. Also, you may need to optimize your SQL statements when querying.

·         You may want to index some frequently used fields in database. It'll save you time when querying.

How to select distinct rows in a DataTable.

A: As we know, we can use Select method to filter a DataTable based on certain fields. However, it doesn't help to select distinct rows in a DataTable. Therefore, we have no way to select distinct rows directly.

After a hard research on MSDN, I found a solution here:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3633630&SiteID=1

First, create a DataView for your table, and apply any filtering and sorting in that dataview.  If you have no filtering or sorting, you can just use originalTable.DefaultView.

Second, call ToTable() on the dataview.  ToTable() has an overload which lets you specify whether or not to return only distinct values, and a params string[] argument to specify which columns you want in the new table.  If you specify true as the first argument, only rows unique within the columns that you specify in the params argument will be returned.  If you want all of the columns from the original table, you can simply specify the boolean argument "true"; if you don't specify any columns, all columns are returned.

Thus, the easiest way to return a new table that has only the unique values from the original table is as follows:

DataTable distinctTable = originalTable.DefaultView.ToTable( /*distinct*/ true);

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

Windows11怎么禁用后台应用程序_Windows11禁用后台应用教程 Windows11怎么禁用后台应用程序_Windows11禁用后台应用教程 May 07, 2024 pm 04:20 PM

1、在Windows11中打开设置。您可以使用Win+I快捷方式或任何其他方法。2、转到应用程序部分,然后单击应用程序和功能。3、查找要阻止在后台运行的应用程序。单击三点按钮并选择高级选项。4、找到【后台应用程序权限】部分并选择所需的值。默认情况下,Windows11设置电源优化模式。它允许Windows管理应用程序在后台的工作方式。例如,一旦启用省电模式以保留电池,系统将自动关闭所有应用程序。5、选择【从不】可防止应用程序在后台运行。请注意,如果您注意到程序不向您发送通知、无法更新数据等,您可

deepseek怎么转换pdf deepseek怎么转换pdf Feb 19, 2025 pm 05:24 PM

DeepSeek 无法直接将文件转换为 PDF。根据文件类型,可以使用不同方法:常见文档(Word、Excel、PowerPoint):使用微软 Office、LibreOffice 等软件导出为 PDF。图片:使用图片查看器或图像处理软件保存为 PDF。网页:使用浏览器“打印成 PDF”功能或专用的网页转 PDF 工具。不常见格式:找到合适的转换器,将其转换为 PDF。选择合适的工具并根据实际情况制定方案至关重要。

无法允许访问 iPhone 中的摄像头和麦克风 无法允许访问 iPhone 中的摄像头和麦克风 Apr 23, 2024 am 11:13 AM

您在尝试使用应用程序时是否收到“无法允许访问摄像头和麦克风”?通常,您可以在需要提供的基础上向特定对象授予摄像头和麦克风权限。但是,如果您拒绝权限,摄像头和麦克风将无法工作,而是显示此错误消息。解决这个问题是非常基本的,你可以在一两分钟内完成。修复1–提供相机、麦克风权限您可以直接在设置中提供必要的摄像头和麦克风权限。步骤1–转到“设置”选项卡。步骤2–打开“隐私与安全”面板。步骤3–在那里打开“相机”权限。步骤4–在里面,您将找到已请求手机相机权限的应用程序列表。步骤5–打开指定应用的“相机”

field在java中是什么意思 field在java中是什么意思 Apr 25, 2024 pm 10:18 PM

在Java中,"field"是类或接口中的数据成员,用于存储数据或状态。field的属性包括:类型(可为任何Java数据类型)、访问权限、static(属于类而非实例)、final(不可变)和transient(不序列化)。field用于存储类或接口的状态信息,例如存储对象数据和维护对象状态。

oracle怎么读取dbf文件 oracle怎么读取dbf文件 May 10, 2024 am 01:27 AM

Oracle 可以通过以下步骤读取 dbf 文件:创建外部表,引用 dbf 文件;查询外部表,检索数据;将数据导入 Oracle 表。

Java反射机制如何修改类的行为? Java反射机制如何修改类的行为? May 03, 2024 pm 06:15 PM

Java反射机制允许程序动态修改类的行为,无需修改源代码。通过Class对象操作类,可以通过newInstance()创建实例,修改私有字段值,调用私有方法等。但应谨慎使用反射,因为它可能会导致意外的行为和安全问题,并有性能开销。

Java 函数开发中常见的异常类型及其修复措施 Java 函数开发中常见的异常类型及其修复措施 May 03, 2024 pm 02:09 PM

Java函数开发中常见的异常类型及其修复措施在Java函数开发过程中,可能遇到各种异常,影响函数的正确执行。以下是常见的异常类型及其修复措施:1.NullPointerException描述:当访问一个还未初始化的对象时抛出。修复措施:确保在使用对象之前对其进行非空检查。示例代码:try{Stringname=null;System.out.println(name.length());}catch(NullPointerExceptione){

vue中iframe跨域的方法 vue中iframe跨域的方法 May 02, 2024 pm 10:48 PM

在 Vue 中解决 iframe 跨域问题的方法:CORS:启用后端服务器中的 CORS 支持,在 Vue 中使用 XMLHttpRequest 或 fetch API 发送 CORS 请求。JSONP:使用后端服务器中的 JSONP 端点,在 Vue 中动态加载 JSONP 脚本。代理服务器:设置代理服务器转发请求,在 Vue 中使用第三方库(如 axios)发送请求并设置代理服务器 URL。

See all articles