Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing SQL query from C# code

I'm trying to execute SQL query from C# code, but it doesn't return any values, but when I write query directly to SQL it works fine.

static int TestGettingData()
{
        int rows;
        string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using (SqlCommand command = new SqlCommand("SELECT [UserName] FROM [aspnet_Users]", connection))
            {
                connection.Open();
                rows = command.ExecuteNonQuery();
            }
        }
        return rows;
}

And connection string:

<connectionStrings>
<add name ="DefaultConnection" connectionString="Server=myServer;
            Database=MyDatabase;User 
            Id=User;
            Password=password;
            MultipleActiveResultSets=True;"
            providerName="System.Data.SqlClient"/>
</connectionStrings>

And TestGettingData() always returning -1.

like image 824
Kamil Rafałko Avatar asked May 10 '26 08:05

Kamil Rafałko


2 Answers

There are multiple ways to get Data out of your Database

ExecuteScalar

if you have one result field you can use

string Command = "SELECT [UserName] FROM [aspnet_Users];";
using (SqlConnection myConnection = new SqlConnection(ConnectionString))
{
    myConnection.Open();
    using (SqlCommand myCommand = new SqlCommand(Command, myConnection))
    {
        string Result = (string)myCommand.ExecuteScalar(); // returns the first column of the first row
    }
}

SqlDataAdapter

if you expect multiple rows / columns you can load it into a DataTable by

string Command = "SELECT [UserName] FROM [aspnet_Users]";
using (SqlConnection myConnection = new SqlConnection(ConnectionString))
{
    using (SqlDataAdapter myDataAdapter = new SqlDataAdapter(Command, myConnection))
    {
        DataTable dtResult = new DataTable();
        myDataAdapter.Fill(dtResult);
    }
}

SqlDataReader

Another solution is the SQLDataReader. E.g. if you want to load all rows of a column into a List. This has less overhead than the DataAdapter.

List<string> Result = new List<string>();
string Command = "SELECT [UserName] FROM [aspnet_Users];";
using (SqlConnection mConnection = new SqlConnection(ConnectionString))
{
    mConnection.Open();
    using (SqlCommand cmd = new SqlCommand(Command, mConnection))
    {
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                Result.Add((string)reader[0]);
            }
        }
    }
}
like image 101
fubo Avatar answered May 12 '26 20:05

fubo


Because documentation say so;

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.

You can use COUNT(*) wiht ExecuteScalar method to get your number.

using (SqlCommand command = new SqlCommand("SELECT COUNT([UserName]) FROM [aspnet_Users]", connection))
{
     connection.Open();
     rows = (int)command.ExecuteScalar();
}
like image 24
Soner Gönül Avatar answered May 12 '26 21:05

Soner Gönül