Addind Data to a SQL data table

Alfie Chadd 61 Reputation points

Afternoon everyone, I have been doing some research on how to use SQL databases and found a guide from microsoft. (

I have tried using this code and changing it to work for my purpose but it has not worked.

Here is the code below if anyone knows how to fix it, Thanks.

private void button1_Click(object sender, EventArgs e)
SqlConnection scn = new SqlConnection();
scn.ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\LoginDB\logindb.mdf;Integrated Security=True;Connect Timeout=30";
SqlCommand scmd = new SqlCommand("select count (*) as cnt from LOGINDB where username=@HideakiUsui and password=@PWD ", scn);
scmd.Parameters.Add(new SqlParameter("@HideakiUsui ", SqlDbType.NChar));
SqlCommand.Parameters["@HideakiUsui "].Value = txt_UserName;
scmd.Parameters.Add(new SqlParameter("@PWD ", SqlDbType.NChar));

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,865 questions
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,099 questions
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,504 questions
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 26,766 Reputation points

    Your code is incomplete. It does not open a connection or execute the query. Also, the query does not Add records to the database. I'm a little confused as to what you are actually trying to accomplish.

    Anyway, you'll want to use the ExecuteScalar() method since you're returning a single value; Count(*). Follow the coding pattern in the ADO.NET reference documentation.

    SqlCommand.ExecuteScalar Method

    Your code will look similar to the following where the username, password, and are passed to a method.

    static public int Authenticate(string username, string password, string connString)  
        Int32 count = 0;  
        string sql = "select count (*) as cnt from LOGINDB where username=@usr and password=@pwd";  
        using (SqlConnection conn = new SqlConnection(connString))  
            SqlCommand cmd = new SqlCommand(sql, conn);  
            cmd.Parameters.Add("@usr", SqlDbType.VarChar);  
            cmd.Parameters["@usr"].Value = username;  
            cmd.Parameters.Add("@pwd", SqlDbType.VarChar);  
            cmd.Parameters["@pwd"].Value = password;  
                count = (Int32)cmd.ExecuteScalar();  
            catch (Exception ex)  
        return (int)count;  

0 additional answers

Sort by: Most helpful