0

I am using Azure function to connect to Sql database and retrieve values. I am able to install the necessary Nuget packages and perform Sql connection and querying in the Run() function

I wish to keep this database access function alone in a separate file, and return value to the main function(Run() in this case). But when i create a new class in the Azure function project and write SQL connection code, no "using" statements can be used or installed packages can be used.

I am new to Azure functions and may be i am wrong in this approach. Can you help me out? Thanks.

enter image description here.

2
  • Yes its MS SQL Server Commented Aug 4, 2020 at 13:16
  • you need to add the needed using statements. Quick FIx sould help out. Also, you are missing a method definition. Commented Aug 4, 2020 at 13:20

2 Answers 2

1

You just need to wrap your code in a method. Here's a sample:

public class SqlQuery
{
    private string cs = Environment.GetEnvironmentVariable("SqlConnectionString");
    
    public void Query()
    {
        using(var conn = new SqlConnection(cs))
        {
            conn.Open();
            var cmd = conn.CreateCommand("SELECT * FROM Table");
            var dr = cmd.ExecuteReader();

            if(dr == null) return;
                        
            while(dr.Read())
            {

            }
        }
    }
    
}
Sign up to request clarification or add additional context in comments.

1 Comment

you're welcome, don't forget to change the return type from void to the object you want and also include the return statement after the while.
1

the screenshot you shared contains a class and has started implementation inside the class, whereas you should be creating at least one method inside your class and then add your code into the method which returns the data you expect. try that it should work!

public class SqlQuery{
public void ExecuteReader()
{
    private string cs =Environment.GetEnvironmentVariable("SqlConnectionString");
    using(var conn = new SqlConnection(cs))
    {
          conn.Open();
          var cmd = conn.CreateCommand("SELECT * FROM Table");
          var dr = cmd.ExecuteReader();
          if(dr == null) return;
          while(dr.Read())
          {

         }
    }
}}

1 Comment

Yea i missed that out in a hurry writing! Thanks.

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.