构造数组时出现问题(在SQL语句之后) [英] Problem constructing an Array (after SQL statement)

查看:117
本文介绍了构造数组时出现问题(在SQL语句之后)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我说实话:这是一个荒谬的问题,我花了一个多小时,因为那四行代码,但是我想不清楚,不知道是否是因为它的5550 am ...

I''ll me honest: its a ridiculous problem, I''ve spent more than hour because those 4 lines of code, but I cant think clearly, dont know if its because its 5550 am...

cmd = new SqlCommand("Select Texto FROM Notes WHERE ID_users='" + id_user.ToString() + "'", conn);
          SqlDataReader dr = cmd.ExecuteReader();
          int num = 9; // static variable to change later
          string[] texto = new string[num];
         
               while (dr.Read())
               {
                   for (int i = 0; i < num; i++)
                   {
                       texto[i] = dr[0].ToString();
                   }
               }



所以问题是,该SQL语句的结果是其简单的9个不同的字符串.我想将它们存储在Array-texto中.

但是由于某些(显而易见的)原因,数组中的所有字段都相同(SQL查询的最后结果).



So the problem is, the result from that SQL statement its simple 9 different strings. And I want to store them in Array - texto.

But for some (obvious) reason, all fields from array gets the same (the last result from sql query).

Can you please help me?

推荐答案

Maxxdd,

您正在使用嵌套循环,这就是问题所在.从此处删除for循环,并在while循环之前声明i,然后在赋值之后递增i.
Hi Maxxdd,

You are using nested loop here that is the problem. Remove for loop from there and declare i before while loop and increment i after assignment.


int i;
i=0;                     
                while (dr.Read())
                {
                  texto[i] = Convert.ToString(dr[0]);
                  i++;
                }



使用convert.ToString因为如果dr [0]中的字符串为null,它将不会通过异常,否则会导致null指针异常



Used convert.ToString Beacuse if the string in dr[0] in null it will not through an exception otherwise it througs null pointer exception


for (int i = 0; i <= dr.RecordsAffected - 1; i++) {
    texto[i] = dr(0);
}



我想添加的一件事是使用sql参数来防止sql注入:

例如:



one more thing i would like to add is to use sql parameters to prevent sql injections :

for example:

cmd = new SqlCommand("Select Texto FROM Notes WHERE ID_users=@Iduser, conn);


SqlParameter param = new SqlParameter();
param.ParameterName = "@Iduser";
param.Value = id_user.ToString();
param.Size = 15;
param.SqlDbType = System.Data.SqlDbType.VarChar;

cmd.Parameters.Add(param);



干杯!



Cheers!


这篇关于构造数组时出现问题(在SQL语句之后)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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