0

I'm pretty new in .net, I hope this question will not sound stupid. How can I do the following sql script to the database in a webmethod in .net c#?

Under Web.config I have code the following code for connecting to the database:

<connectionStrings>
    <add name="TestConnectionString" connectionString="Data Source=TXT-TEST-SQL-02;Initial Catalog=Test;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>

How can I do under test.asmx.cs - webmethod to run the following script from the database to retrieved the data from the table?

[WebMethod]
public string testSearch(int id)
{
    return result;
}

SELECT name
FROM Customer
WHERE customer_id = id

1 Answer 1

3

Try

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;

and

[WebMethod]
public string testSearch(int id)
{
    string connString = ConfigurationManager.ConnectionStrings["TestConnectionString"].ConnectionString;
    using (SqlConnection conn = new SqlConnection(connString))
    {

        String sql = "SELECT name FROM Customer WHERE customer_id = @id";
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.Parameters.Add("@id", SqlDbType.Int);
        cmd.Parameters["@id"].Value = id;
        String result = "";
        try
        {
            conn.Open();
            result = (string)cmd.ExecuteScalar();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        return result;
    }
}
Sign up to request clarification or add additional context in comments.

8 Comments

@Bala:It's show me error that said ' The name 'ConfigurationManager' does not exist in the current context
@Jin Yong make sure you have all the required using.
@Bala: cool... this is working for me now, but If I run the script will return more then 1 record, can I still using ExecuteScalar()? or I should use other function to retrieve those records and assign into result in array format?
@Jin yes ExecuteScalar will pick the first record.
@Bala: how about if I want to retrieve all records instead of the 1st record only? how can I do it? example if I run the following script [select name from customer order by customer name]
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.