【发布时间】:2020-04-23 21:54:05
【问题描述】:
我目前正在构建一个考勤跟踪器,它将获取用户的输入数据并将其添加到数据库表中。我遇到了我的连接字符串无法连接到数据库的问题?我直接照原样复制了它,甚至用其他方法尝试了一些不同的教程,但没有成功。这是一个作业,但是,我们的 SQL 部分很小,我不知道从哪里开始。如果我的代码中的某些内容需要重新访问,请告诉我。
当我运行代码时,我得到了我在下面创建的“无法连接”异常。我需要它来运行并将用户输入添加到表中。
我也注意到我的数据库连接经常断开,除非我刷新,这很常见吗?
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.");
}
}
【问题讨论】:
-
看看异常说了什么,里面包含了连接失败的原因。
-
这并没有让我回去看看为什么连接失败。未列出原因。
-
异常信息到底是什么? stacktrace 指向哪一行?
-
我必须删除我的 try/catch 才能看到错误。陈述:System.Data.SqlClient.SqlException:'必须声明标量变量“@studentName”。'
标签: c# sql database visual-studio windows-forms-designer