Share via


how to store value from sql database to variable c#

Question

Monday, June 10, 2013 9:27 AM

i have a table "login" column "pin" sql database

i want to store value from column "pin" to variable in c#

database sqli have made store procedure of login.

All replies (4)

Monday, June 10, 2013 10:11 AM ✅Answered

You could do it by using a SqlDataReader, as follows:

List<int> lst = new List<int>();
string query = "SELECT [pin] FROM dbo.login;";

try {
    using (SqlConnection con = new SqlConnection(conStr)) {
        SqlCommand cmd = new SqlCommand(query, con);
        con.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        while (reader.Read()) {
            lst.Add(reader.GetInt32(0));
        }
        reader.Close();
    }
} catch (Exception e) {
    Console.WriteLine(e.StackTrace + "\n\n" + e.Message);
}

In my snippet I use a List<int> to put the value in, but you could use a simple variable as well.

wizend


Monday, June 10, 2013 10:10 AM

Hi,

You can ref  Calling Stored procedures in ADO.NET

亂馬客blog: http://www.dotblogs.com.tw/rainmaker/


Monday, June 10, 2013 10:24 AM

How does your stored procedure look like?

 

Noam B.

Do not Forget to Vote as Answer/Helpful, please. It encourages us to help you...


Monday, June 10, 2013 3:14 PM

USE [givenget]
GO
/****** Object:  StoredProcedure [dbo].[logina]    Script Date: 06/10/2013 20:13:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[logina] @pin varchar (50)
as
INSERT INTO [givenget].[dbo].[login]

           (
           [pin]
           )
     VALUES
           (
           @pin
           )

I am passing just one parameter, I want value of 'pin' to store in variable c#