我试图在Server上执行,但是它返回了一个错误,我不知道真正的问题是什么。这是我尝试过的一些代码。
这是一个错误:

代码:
SqlConnection connection = new SqlConnection("Data Source=LOCALHOST\\SQLEXPRESS;Initial Catalog=tempdb;Integrated Security=SSPI;User ID = xxxx; Password=xxx;");
DateTime dt = dateTimePicker1.Value.Date;
dt = dt.AddDays(60);
string selectQuery = "BEGIN TRANSACTION UPDATE tester SET
test_ad=@dateTimePicker1, test_ud=@dt, test_pd=@dt WHERE
test_name=@textBox1;INSERT INTO records(testr_status, testr_name, testr_ad,
testr_ud, testr_pd, apte_name)VALUES(@testr_status, testr_name = @comboBox1,
testr_ad = @dateTimePicker1, testr_ud = @dt, testr_pd = @dt COMMIT";
connection.Open();
SqlCommand command = new SqlCommand(selectQuery, connection);
command.Parameters.AddWithValue("@dateTimePicker1",this.dateTimePicker1.Value.Date);
command.Parameters.AddWithValue("@textBox1", this.textBox1.Text);
command.Parameters.AddWithValue("@comboBox1",this.comboBox1.SelectedItem);
command.Parameters.AddWithValue("@testr_status",SqlDbType.VarChar);
command.Parameters.AddWithValue("@dt", dt);
int iResult = command.ExecuteNonQuery();
if (iResult > 0)
MessageBox.Show("Successfully saved ", "Error",MessageBoxButtons.OK, MessageBoxIcon.Information);
else
MessageBox.Show("Record not saved ", "Error",MessageBoxButtons.OK, MessageBoxIcon.Error);
command.ExecuteNonQuery();
connection.Dispose();
command.Dispose();发布于 2018-06-27 04:31:43
尝试清理一下您的查询,或者将其粘贴到SSMS上,并声明您的参数,您就会发现出了什么问题。
在您的示例中,您的INSERT语句有一些错误。
VALUES (test_name = @combobox1),而是只传递参数VALUES (@combobox1)INSERT语句中的列比VALUES子句中指定的值多,因此没有为apte_name提供值。在c#代码中,您也需要添加该参数。VALUES子句的结尾括号你应该得到这样的结果(没有经过测试)。
string selectQuery =
@"BEGIN TRANSACTION
UPDATE tester SET
test_ad = @dateTimePicker1,
test_ud = @dt,
test_pd = @dt
WHERE test_name = @textBox1;
INSERT INTO records
(
testr_status,
testr_name,
testr_ad,
testr_ud,
testr_pd,
apte_name
)
VALUES
(
@testr_status,
@comboBox1,
@dateTimePicker1,
@dt,
@dt,
@apte_name
);
COMMIT";发布于 2018-06-27 04:43:37
实际问题是,这是一个大的无效SQL语句。使用分号分隔语句,如下所示:
"BEGIN TRANSACTION;
INSERT ...;
UPDATE ...;
ETC ...;
COMMIT;"这就是说,不要在查询字符串中嵌入事务语句。照奥利弗在另一个答案中的建议去做。
发布于 2018-06-27 03:22:37
您可以使用SqlTransaction
using (SqlConnection conn = new SqlConnection("Connection String"))
{
conn.Open();
SqlTransaction trans;
trans = conn.BeginTransaction();
string selectQuery = "your sql query";
SqlCommand command = new SqlCommand(selectQuery, connection);
int iResult = command.ExecuteNonQuery();
if (iResult > 0)
{
trans.Commit();
}else{
trans.Rollback();
}
conn.Close();
}https://stackoverflow.com/questions/51054005
复制相似问题