使用方法ExecuteScalar解释代码。我是新手。我只是想了解代码的作用。不同的代码行是什么意思 [英] explanation for code using method ExecuteScalar. am a newbie here. I just want to understand what the code does. What the different lines of code mean

查看:128
本文介绍了使用方法ExecuteScalar解释代码。我是新手。我只是想了解代码的作用。不同的代码行是什么意思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

字符串str1 =从UserInfo中选择count(*),其中[UserName] =''+ this.CreateUserWizard1.UserName.Trim()+''; 
OleDbConnection conn = new OleDbConnection(ASPNETDB);
OleDbCommand cmd = new OleDbCommand(str1,conn);
conn.Open();
Int32 dr2 =(Int32)cmd.ExecuteScalar();
dr2 = Convert.ToInt32(dr2);
if(dr2> 0)

解决方案

这里它逐行分解:



1.此行创建一个字符串变量并为其指定一个select语句值。



2.此行实例化一个新的OleDbConnection 。



3.此行实例化一个新的OleDbCommand。



4.此行打开连接到数据库。



5.此行创建一个Int32变量并为其指定ExecuteScalar()方法的返回值。



6.这一行将Int32变量转换为Int32(为什么?)。



7.这一行只是if语句的一小部分但检查dr2是否大于0.


ExecuteScalar在数据库上执行请求并返回第一个答案(行和列)。

在你的情况下应该是 UserInfo 中的行数( count(*))表格 UserName 是指定的用户名。



但我不明白需要演员和转换! dr2是一个Int32,没有必要将它转换为Int32。



但是在(Int32)强制转换之前检查结果的类型应避免任何异常。

String str1 = "select count(*) from UserInfo where [UserName]=''" + this.CreateUserWizard1.UserName.Trim() + "''";
            OleDbConnection conn = new OleDbConnection("ASPNETDB");
            OleDbCommand cmd = new OleDbCommand(str1, conn);
            conn.Open();
            Int32 dr2 = (Int32)cmd.ExecuteScalar();
            dr2 = Convert.ToInt32(dr2);
            if (dr2 > 0)

解决方案

Here it is broken down line by line:

1. This line creates a string variable and assigns it a select statement value.

2. This line instantiates a new OleDbConnection.

3. This line instantiates a new OleDbCommand.

4. This line opens the connection to the database.

5. This line creates an Int32 variable and assigns it the returned value of the ExecuteScalar() method.

6. This line converts the Int32 variable to an Int32(why?).

7. This line is only a fraction of an if statement but checks whether dr2 is greater than 0.


ExecuteScalar execute the request on the database and returns the first answer (row and column).
In your case in should be the number of row (count(*))in UserInfo table where UserName is the username specified.

But I do not understand the need of the cast and Convert! dr2 is an Int32, there is no need to convert it to Int32.

But checking the type of result before (Int32) cast should avoid any exception.


这篇关于使用方法ExecuteScalar解释代码。我是新手。我只是想了解代码的作用。不同的代码行是什么意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆