0

I am trying to update my vote count in my SQL Server database each time the "vote" button is pressed after selecting a candidate from my radiobutton list.

The radio button list has 3 candidates, and once a candidate is selected, the vote button is pressed. I want my database to update once the vote button is pressed. However, I have tried many different solutions, and was unsuccessful.

My database has a table with an Id key (numerical ID), Name (name of candidates), and Vote (number of votes of corresponding candidate).

Here is my newest attempt:

public void update_db(string candidate)
{
    const string connString = @"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename =| DataDirectory |\Candidates.mdf; Integrated Security = True";

    SqlConnection conn = new SqlConnection(connString);
    conn.Open();

    SqlCommand cmd = new SqlCommand("UPDATE Vote SET Vote=Vote+1 WHERE name='" + candidate + "'", conn);
    cmd.ExecuteNonQuery();
    conn.Close();
}

However, when I run my project, I the following error on the following line:

SqlConnection conn = new SqlConnection(connString);

System.ArgumentException: 'Invalid value for key 'attachdbfilename'.'

I also tried changing UpdateQuery for SqlDataSource1 from the properties menu on Visual Studio.

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
     ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
     SelectCommand="SELECT * FROM [Table]" 
     UpdateCommand="UPDATE Candidates SET Vote = Vote+1 WHERE Vote = @id2 ">
     <UpdateParameters>
         <asp:ControlParameter ControlID="RadioButtonList1" Name="id2" PropertyName="SelectedValue" />
     </UpdateParameters>
</asp:SqlDataSource>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • [SQL Injection alert](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - you should **not** concatenate together your SQL statements - use **parametrized queries** instead to avoid SQL injection - check out [Little Bobby Tables](http://bobby-tables.com/) – marc_s Apr 25 '21 at 06:09
  • Please see [Bad habits: Using AttachDBFileName](https://www.sentryone.com/blog/aaronbertrand/bad-habits-attachdbfilename) and https://stackoverflow.com/questions/11178720/whats-the-issue-with-attachdbfilename – Charlieface Apr 25 '21 at 08:47

1 Answers1

2

It needs to be provided with no spaces:

AttachDbFilename=|DataDirectory|\Filename.mdf

Please note you can use an absolute path if that's desired:

AttachDbFilename=C:\MyDatabases\Filename.mdf
tymtam
  • 31,798
  • 8
  • 86
  • 126