简体   繁体   中英

Connection String Not Working- Not Allowing Connection to Database made in VS (C# Visual Studio)

I am currently working on building an attendance tracker that will take the user's input data and add it to a database table. I'm running into an issue where my connection string will not connect to the database? I've copied it directly as is, and even tried a few different tutorials with alternative ways with no success. This is for an assignment however, our SQL portion was quite small and I'm not sure where to go from here. Please let me know if something in my code needs revisited.

When I run the code I get the "unable to connect" exception I created below. I need it to run and add the user input to the table.

I have also noticed that my database connection often disconnects unless I refresh, is this common?

namespace AttendanceTracker
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void signInButton_Click(object sender, EventArgs e)
    {
        string connectionString = null;
        connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\soupy\Desktop\AttendanceTracker\AttendanceTrackerDatabase.mdf; Integrated Security = SSPI";
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;

        cmd.CommandText = ("INSERT into AttendanceTrackerDatabase VALUES (@studentName,@studentID,@Date,@class)");

        cmd.Parameters.AddWithValue("@Student_Name", nameTextBox.Text);
        cmd.Parameters.AddWithValue("@Student_ID", studentIDTextBox.Text);
        cmd.Parameters.AddWithValue("@Class", classDropDown.Text);
        cmd.Parameters.AddWithValue("@Date", attendanceDate.Value);

        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
            MessageBox.Show("Your sign in has been recorded successfully!");
            con.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Unable to open attendance tracker for updating.");
        }
    }

When using Parameter objects , you should ensure that the variable names are consistent.

Please modify your code as follows

cmd.CommandText = ("INSERT into AttendanceTrackerDatabase VALUES (@studentName,@studentID,@Date,@class)");

cmd.Parameters.AddWithValue("@studentName", nameTextBox.Text); // Modified to "studentName"
cmd.Parameters.AddWithValue("@studentID", studentIDTextBox.Text); // Modified to "studentID"
cmd.Parameters.AddWithValue("@Date", attendanceDate.Value);
cmd.Parameters.AddWithValue("@class", classDropDown.Text); // Modified to "class"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM