Return value of a select statement
Asked Answered
M

7

6

I want to retrieve the resulting value of a select statement into a string variable like this:

OleDbCommand cmd1 = new OleDbCommand();
cmd1.Connection = GetConnection();
cmd1.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
cmd1.ExecuteNonQuery();
     

I want to place the selected treatment value into a string variable. How can I do this?

Magnoliamagnoliaceous answered 26/12, 2012 at 13:28 Comment(2)
Start by avoiding the "...NonQuery" method. Non-Query means "don't return any value from executing this command."Alehouse
Use ExecuteReader() to get a datareader and call Read(0) on the datareaderSweatbox
G
24

Use ExecuteReader() and not ExecuteNonQuery(). ExecuteNonQuery() returns only the number of rows affected.

try
{
    SqlDataReader dr = cmd1.ExecuteReader();
}
catch (SqlException oError)
{

}
while(dr.Read())
{
    string treatment = dr[0].ToString();
}

Or better, use a using statement for it.

using(SqlDataReader dr = cmd1.ExecuteReader())
{
    while(dr.Read())
    {
        string treatment = dr[0].ToString();
    }
}

But if your SqlCommand returns only 1 column, you can use the ExecuteScalar() method. It returns first column of the first row as follows:-

cmd.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
string str = Convert.ToString(cmd.ExecuteScalar());

Also you can open your code to SQL Injection. Always use parameterized queries. Jeff has a cool blog article called Give me parameterized SQL, or give me death. Please read it carefully. Also read DotNetPerl SqlParameter article. SQL Injection very important when you are working queries.

Gonsalves answered 26/12, 2012 at 13:30 Comment(3)
Soner you should recommend to the OP to wrap his ExecutReader() Method be wrapped around a try{}catchDillingham
@DJKRAZE Good idea. Updated.Sheriesherif
I'll stress that this is not a good solution in the big picture. It answers the question, but does not fix the sql injection issues.Attaint
D
4

Execute Scalar: Getting Single Value from the Database method to retrieve a single value (for example, an aggregate value) from a database.

cmd1.Connection = GetConnection();
cmd1.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
if(cmd.ExecuteScalar()==null)
{
    var treatment = cmd.ExecuteScalar();
}

Other Way: ExecuteReader()

try
{
    cmd1.CommandText ="SELECT treatment FROM appointment WHERE patientid=@patientID";
    cmd1.Parameters.AddWithValue("@patientID", this.DropDownList1.SelectedValue);

    conn.Open();
    SqlDataReader dr = cmd1.ExecuteReader();
    while (dr.Read())
    {
        int PatientID = int.Parse(dr["treatment"]);
    }
    reader.Close();
    ((IDisposable)reader).Dispose();//always good idea to do proper cleanup
}
catch (Exception exc)
{
    Response.Write(exc.ToString());
}
Drawee answered 26/12, 2012 at 13:36 Comment(4)
Vishak, you are issuing a cmd1.ExecuteReader() what do you do if there is more than 1 row that's returned..? shouldn't you check if reader.HasRows or do the reader.Read() in a While Loop..??? you are assuming that the query will only return 1 row in that case you need to use the ExecuteScalar()Dillingham
Also look at this Link msdn.microsoft.com/en-us/library/… you have int PatientID= reader.GetOrdinal("treatment"); where is the while loop to read the next records if any..?Dillingham
how are you passing back int PatientID = int.Parse(dr["treatment"]); it's not accessible outside that Try is PatiendID a variable that should be declared in a different scope..?Dillingham
+1 for clean code.. but I would ask OP how he plans to return the PatientID you may want to declare that as a Session["PatientID"] or as a Protected Property if we are talking about Web Application or a Property .. I hate to assume but I am going to guess this is a Windows ApplicationDillingham
H
1

the answer:

String res = cmd1.ExecuteScalar();

the remark: use parametrized query to prevent sql injection

Hollah answered 26/12, 2012 at 13:31 Comment(1)
this is good but you are assuming that the OP's query will always return 1 record.. also this is not a good example of how to answer the OP's question why not paste in his code with the working solutionDillingham
A
1

There is a lot wrong with your example code.

  1. You have inline sql, which opens you up to sql injection in a major way.
  2. You are using ExecuteNonQuery() which means you get no data back.

     string sSQL = "SELECT treatment FROM appointment WHERE patientid = @patientId";
     OleDbCommand cmd1 = new OleDbCommand(sSQL, GetConnection()); // This may be slight different based on what `GetConnectionReturns`, just put the connection string in the second parameter.
    
    
        cmd1.Parameters.AddWithValue("@patientId", text);
        SqlDataReader reader = cmd1.ExecuteReader();
        string returnValue;
        while(reader.Read())
        {
           returnValue = reader[0].ToString();
        }
    
Attaint answered 26/12, 2012 at 13:36 Comment(2)
Where is the Select Statement in your example.. ?Dillingham
Hrm, lost it in translation somewhere. I've added it.Attaint
M
0

You just need to use the ExecuteScalar method of the command - this will give you the value at the first row and column of the result set.

OleDbCommand cmd1 = new OleDbCommand();
cmd1.Connection = GetConnection();
cmd1.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
var result = cmd1.ExecuteScalar();

If your SQL statement returns more than one row/column then you can use ExecuteReader().

Manon answered 26/12, 2012 at 13:31 Comment(0)
G
0

You need to use OleDbAdapter.

string connection = "your connection";
string query = "SELECT treatment FROM appointment WHERE patientid = " + text;
OleDbConnection conn = new OleDbConnection(connection);
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = new OleDbCommand(query, conn);
adapter.Fill(dataset);
Garbage answered 26/12, 2012 at 13:35 Comment(1)
Cristoleg, he can do this without using OleDBAdapterDillingham
V
0
SqlConnection dbConnect = new SqlConnection("your SQL connection string");    
string name = " 'ProjectName' ";
string strPrj = "Select e.type, (e.surname +' '+ e.name) as fulln from dbo.tblEmployees e where id_prj = " + name;
        SqlCommand sqlcmd = new SqlCommand(strPrj, dbConnect);
        SqlDataAdapter sda = new SqlDataAdapter(strPrj, dbConnect);
        ds = new DataSet();
        sda.Fill(ds);
        dbConnect.Open();
        sqlcmd.ExecuteNonQuery();
        dbConnect.Close();
Valiancy answered 27/10, 2014 at 7:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.