【发布时间】:2019-10-23 19:48:49
【问题描述】:
我正在开发一个应用程序,但遇到了这个问题。我正在尝试向我的 SQL 本地数据库添加一条记录。它给出了成功的消息框,但是当我关闭应用程序并检查表格时,记录不存在。我尝试以两种不同的方式添加它,但都没有奏效。我把代码贴在这里
这是我尝试的第一种方法
using (SqlConnection _conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Restaurant.mdf;Integrated Security=True"))
{
using (SqlCommand _cmd = new SqlCommand("INSERT INTO Chelneri(username, nume, prenume, email, parola) values ('" + textBoxUser.Text.ToString().Trim() +"', '"+ textBoxNume.Text.ToString().Trim() +"', '"+ textBoxPrenume.Text.ToString().Trim() +"', '"+ textBoxEmail.Text.ToString().Trim() +"', '"+ textBoxParola.Text.ToString().Trim() +"')", _conn))
{
try
{
_conn.Open();
_cmd.ExecuteNonQuery();
_conn.Close();
textBoxUser.Text = string.Empty;
textBoxNume.Text = string.Empty;
textBoxPrenume.Text = string.Empty;
textBoxParola.Text = string.Empty;
textBoxEmail.Text = string.Empty;
MessageBox.Show("Utilizatorul a fost creat!", "Restaurant Casa Verde", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString(), "Restaurant Casa Verde", MessageBoxButtons.OK, MessageBoxIcon.Error);
_conn.Close();
}
}
}
这是第二个。
using (SqlConnection _conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Restaurant.mdf;Integrated Security=True"))
{
using (SqlCommand _cmd = new SqlCommand("INSERT INTO Chelneri(username, nume, prenume, email, parola) values (@user, @nume, @prenume, @email, @parola)", _conn))
{
try
{
_conn.Open();
_cmd.Parameters.Clear();
_cmd.Parameters.Add("@user", SqlDbType.NVarChar).Value = textBoxUser.Text.ToString().Trim();
_cmd.Parameters.Add("@email", SqlDbType.NVarChar).Value = textBoxEmail.Text.ToString().Trim();
_cmd.Parameters.Add("@nume", SqlDbType.NVarChar).Value = textBoxNume.Text.ToString().Trim();
_cmd.Parameters.Add("@prenume", SqlDbType.NVarChar).Value = textBoxPrenume.Text.ToString().Trim();
_cmd.Parameters.Add("@parola", SqlDbType.NVarChar).Value = textBoxParola.Text.ToString().Trim();
_cmd.ExecuteNonQuery();
_conn.Close();
textBoxUser.Text = string.Empty;
textBoxNume.Text = string.Empty;
textBoxPrenume.Text = string.Empty;
textBoxParola.Text = string.Empty;
textBoxEmail.Text = string.Empty;
MessageBox.Show("Utilizatorul a fost creat!", "Restaurant Casa Verde", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString(), "Restaurant Casa Verde", MessageBoxButtons.OK, MessageBoxIcon.Error);
_conn.Close();
}
}
}
【问题讨论】:
-
我想你没有得到任何错误,是吗?我也看到没有交易。因此,如果插入没有抛出,则应该创建记录。这听起来可能很愚蠢,但您是否确认您正在连接到正确的数据库?
-
此外,当您使用带有
using子句的SqlConnection时,您不需要手动关闭它。
标签: c# sql database visual-studio tsql