连接字符串不工作-不允许连接到VS(C#Visual Studio)中创建的数据库
我目前正在构建一个考勤跟踪器,它将获取用户的输入数据并将其添加到数据库表中。我遇到连接字符串无法连接到数据库的问题?我直接照着原样复制了它,甚至尝试了几种不同的教程,但都没有成功。这是一个任务,但是,我们的SQL部分相当小,我不知道从这里去哪里。如果代码中的某些内容需要重新访问,请告诉我 当我运行代码时,我得到下面创建的“无法连接”异常。我需要它运行并将用户输入添加到表中 我还注意到我的数据库连接经常断开,除非我刷新,这是常见的吗连接字符串不工作-不允许连接到VS(C#Visual Studio)中创建的数据库,c#,sql,database,visual-studio,windows-forms-designer,C#,Sql,Database,Visual Studio,Windows Forms Designer,我目前正在构建一个考勤跟踪器,它将获取用户的输入数据并将其添加到数据库表中。我遇到连接字符串无法连接到数据库的问题?我直接照着原样复制了它,甚至尝试了几种不同的教程,但都没有成功。这是一个任务,但是,我们的SQL部分相当小,我不知道从这里去哪里。如果代码中的某些内容需要重新访问,请告诉我 当我运行代码时,我得到下面创建的“无法连接”异常。我需要它运行并将用户输入添加到表中 我还注意到我的数据库连接经常断开,除非我刷新,这是常见的吗 namespace AttendanceTracker { pu
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.");
}
}
使用参数对象时,应确保变量名称一致 请修改您的代码如下
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"
看看这个异常是怎么说的,它包括了连接失败的原因。但它并没有给我一个返回的地方,让我看看连接失败的原因。没有列出原因。具体的异常消息是什么?stacktrace指向哪一行?我必须删除try/catch以查看错误。声明:System.Data.SqlClient.SqlException:'必须声明标量变量“@studentName”。'