控制台应用程序中的SQL语句导致错误

时间:2016-03-15 19:30:29

标签: c# sql

我使用此查询字符串:

string queryString = "SELECT email_uzivatele from Reklama where email_uzivatele like '%" + @email_uzivatele + "%'";

在控制台应用程序中测试它。

当字符串是这样的时候:

string queryString = "SELECT * from Reklama where email_uzivatele like '%" + @email_uzivatele + "%'";

它工作正常。但是当我选择这样的特定列时:

string queryString = "SELECT email_uzivatele from Reklama where email_uzivatele like '%" + @email_uzivatele + "%'";

它无法正常工作并导致此错误:

  

System.FormatException:输入字符串的格式不正确   at System.Number.StringToNumber(String str,NumberStyles options,NumberBuffer& number,NumberFormatInfo info,Boolean parseDecimal)
  在System.Number.ParseInt32(String s,NumberStyles style,NumberFormatInfo info)
  在System.Int32.Parse(String s)
  在Smart:Advertising.DatabaseLayer.AdvertDatabaseLayer.SelectByEmail(String email_uzivatele)的f:\ BP \ SmartAdvertising.GuiMvc \ Smart.Advertising.DatabaseLayer \ AdvertDatabaseLayer.cs:第228行

我不明白为什么......

请你能帮帮我吗?

编辑:这是我的控制台应用程序中的更多代码:

namespace ConsoleApplication1
{
    class Program
    {
        public static void Main(string[] args)
        {
            AdvertDatabaseLayer.Instance.SelectByEmail("jan");
        }
    }
}

此行导致错误:

AdvertDatabaseLayer.Instance.SelectByEmail("jan");

这是我使用查询字符串的数据库层:

public List<Advert> SelectByEmail(string email_uzivatele)
{
    string queryString = "SELECT email_uzivatele from Reklama where email_uzivatele like '%" + @email_uzivatele + "%'";
    SqlCommand command = new SqlCommand(queryString, Connection);

    command.Parameters.AddWithValue("@email_uzivatele", "");

    try
    {
        SqlDataReader reader = command.ExecuteReader();
        List<Advert> advert = new List<Advert>();
        while (reader.Read())
        {
            Advert a = new Advert();
            a.id_reklamy = int.Parse(reader[0].ToString());
            a.nazev_reklamy = reader[1].ToString();
            a.typ_reklamy = reader[2].ToString();
            a.cena_reklamy = int.Parse(reader[3].ToString());
            a.email_uzivatele = reader[4].ToString();
            a.datumz = reader[5].ToString();
            a.datumk = reader[6].ToString();

            Console.WriteLine("email_uzivatele: " + " " + " " + a.email_uzivatele);

            advert.Add(a);
        }

        reader.Close();
        return advert;
    }
    catch (Exception ex)
    {
        chyba.zapsat_do_souboru(ex.Message);
        Console.OpenStandardOutput();
        Console.WriteLine(ex);
        //zalogovat chybu
        return null;
    }
}

1 个答案:

答案 0 :(得分:0)

我找到解决方案问题我循环遍历所有参数但是在查询字符串中我只有一个参数,所以解决方案是这样的:

  while (reader.Read())
                {

                    Advert a = new Advert();
                    a.email_uzivatele = reader[0].ToString();



                    Console.WriteLine("email_uzivatele: " + " " + " " + a.email_uzivatele);

                    advert.Add(a);
                }