当我尝试执行代码时,我收到了一条错误消息......
变量x
正常运行并显示预期值,textBoxes
也是如此。并且连接是开放的并且正常工作,因为代码块在它工作正常之前!
string x = ViaClass.name;
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = (@"myconString;Integrated Security=YES");
command.Connection = connection;
try
{
connection.Open();
command.CommandText = "IF NOT EXISTS (SELECT 1 FROM ADDRESSES WHERE USID =" + "'" + x + "'" +")" + " INSERT INTO ADDRESSES " + "(AddressLine1, AddressLine2, PostCode) VALUES " + " (@AddressLine1, @AddressLine2, @PostCode)";
command.Parameters.AddWithValue("@AddressLine1", addressLine1TextBox.Text);
command.Parameters.AddWithValue("@AddressLine2", addressLine2TextBox.Text);
command.Parameters.AddWithValue("@PostCode", postCodeTextBox.Text);
int result = command.ExecuteNonQuery();
if (result > 0) MessageBox.Show("Record successfully added!");
else MessageBox.Show("Failed to add record!");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
connection.Close();
}
我的SQL有什么问题吗?我正在使用SQL Server和C#
第一个sql的屏幕截图
答案 0 :(得分:1)
如果声明:
IF NOT EXISTS (SELECT 1 FROM ADDRESSES WHERE USID =" + "'" + x + "'" +")
是假的,那么
result = 0
您的数据是否已存在于数据库中?
有关此验证的有效声明,请
command.CommandText = "IF NOT EXISTS (SELECT 1 FROM ADDRESSES WHERE USID =" + "'" + x + "'" +")" + " INSERT INTO ADDRESSES " + "(AddressLine1, AddressLine2, PostCode) VALUES " + " (@AddressLine1, @AddressLine2, @PostCode) ELSE SELECT 1";
但我不认为有一个' IF'在更新之前,检查会影响行数,这是检查操作是否成功的好方法。