SqlCeCommand.ExecuteScalar does not return a value from the second row of the table

I am trying to create a simple Windows form that retrieves a value from a SQL Server CE database. The table Employeehas 2 columns, nameand company.

The lines are as follows:

Name Company
XXX    ABC
YYY    DEF

I used the following code to extract data from db:

private void button1_Click(object sender, EventArgs e)
{
    string conn = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
    SqlCeConnection con = new SqlCeConnection(conn);

    SqlCeCommand cmd = new SqlCeCommand("select company from EMPLOYEES where name = @name", con);
    cmd.Parameters.AddWithValue("@name",textBox1.Text);

    con.Open();

    try
    {
        object obj = new object();
        obj = cmd.ExecuteScalar();
        label1.Text = (string)obj;
    }
    finally
    {
    }

The above code works fine for the first row in the table. When I specify XXX in the text box, ABC is displayed on the form. But when I enter YYY in the text box, null is returned. I am a fan of C #. Just try some simple examples to learn. Please help me with this. thanks

in advance.

+4
source share
3 answers

. SqlCeCommand.ExecuteScalar 1- .

: SqlCeCommand.ExecuteScalar MSDN:

, . .

ExecuteReader(), 1 .

+3

ExecuteScalar() ( ). Count (*) .

, . , SqlCeDataReader

SqlCeCommand cmd = new SqlCeCommand("select company from EMPLOYEES where name = @name");
cmd.Parameters.AddWithValue("@name",textBox1.Text);

cmd.Connection = con;
con.Open();

SqlCeDataReader dr = selectSQL.ExecuteReader();
while (dr.Read())
  {
    label1.Text = dr["ColumnName"].ToString();
  }
dr.Close();
con.Close();
+1

XXX SQL Management Studio:

update EMPLOYEES set Company = 'ZYX' where Name = 'XXX'

, XXX. ABC, .

By the way, I tried my code myself and it returns the string YYY, so I think this is a data / connection problem.

(FYI, I should have made this a response rather than a comment, because it will not allow me to comment yet.)

0
source

All Articles