Ronald Araújo
Ronald Araújo

Reputation: 1479

Error querying the database for the first time

I have a curious problem. When do the first query in the database it's wrong, but on the second attempt it works perfectly, and not of the problem. What do I need to run it first?

This is the action button:

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(AcessoBD.ConnectionString);

    try
    {
        con.Open();

        SqlCommand cmd = new SqlCommand("con", con);
        //cmd.CommandType = CommandType.Text;
        cmd.CommandText = "SELECT * FROM usuario";

        //cmd.ExecuteNonQuery();

        SqlDataReader dr = cmd.ExecuteReader();

        if (dr.Read())
        {
           MessageBox.Show(dr["usuario"].ToString());
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        con.Close();
    }
}

Class AcessoBD:

public class AcessoBD
{
        static public String ConnectionString
        {
            get
            {    // pega a string de conexão do web.config
                return ConfigurationManager.ConnectionStrings["Conexao"].ConnectionString;
                //return WebConfigurationManager.ConnectionStrings["Conexao"].ConnectionString;
            }
        }
    }

App.config:

<connectionStrings>
   <add name="Conexao"
        connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Base\Database.mdf;Integrated Security=True"
        providerName="System.Data.SqlClient" />
</connectionStrings>

Upvotes: 0

Views: 75

Answers (2)

carleson
carleson

Reputation: 748

Yes, it looks like you run two questions.

Change this:

SqlCommand cmd = new SqlCommand("con", con);
cmd.CommandText = "SELECT * FROM usuario"; 

To:

SqlCommand cmd = new SqlCommand("SELECT * FROM usuario", con);

Upvotes: 0

HaMeD
HaMeD

Reputation: 359

That's because of this line :

cmd.ExecuteNonQuery();

just remove it.

ExcuteNonQuery used for executing queries that haven't any table result like INSERT INTO ...

In this line :

MessageBox.Show(dr["usuario"].ToString());

if you want to get a string from a table you should use like this:

MessageBox.Show(dr.GetString(colIndex));

Upvotes: 2

Related Questions