question

AlfieChadd-1679 avatar image
0 Votes"
AlfieChadd-1679 asked AlfieChadd-1679 edited

Addind Data to a SQL data table

Afternoon everyone, I have been doing some research on how to use SQL databases and found a guide from microsoft. (https://docs.microsoft.com/en-us/visualstudio/data-tools/create-a-simple-data-application-by-using-adonet?view=vs-2022)

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=@usr and password=@pwd", scn);
scmd.Parameters.Clear();
scmd.Parameters.Add(new SqlParameter("@usr", SqlDbType.NChar));
SqlCommand.Parameters["@usr"].Value = txt_UserName;
scmd.Parameters.Add(new SqlParameter("@pwd", SqlDbType.NChar));

         }







sql-server-generaldotnet-csharpwindows-forms
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

AgaveJoe avatar image
0 Votes"
AgaveJoe answered AlfieChadd-1679 edited

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;
            
         try
         {
             conn.Open();
             count = (Int32)cmd.ExecuteScalar();
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.Message);
         }
     }
     return (int)count;
 }



· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Ok thanks :) and Im trying to create an add new account system for a login program

0 Votes 0 ·