如何插入数据库SQL事务?

时间:2019-10-05 11:00:32

标签: c# sql sql-server ado.net sqlcommand

我有一个Log方法:

public void Log(string log)
{
   command = new SqlCommand() { Connection = connection };
   command.CommandText = "INSERT INTO Logs (Date, Login, Transact) " +
      $"VALUES ('{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}', '{Login}', '{log}')";
   connection.Open();
   command.ExecuteNonQuery();
   connection.Close();
}

在日志字符串中,我有一个像这样的值:

"INSERT '/*something*/'"

"UPDATE: '/*smth*/' => '/*smth*/'"

但是它不起作用-我收到错误消息:

  

语法错误

我该怎么办?

1 个答案:

答案 0 :(得分:1)

command.CommandText = "INSERT INTO Logs (Date, Login, Transact) " +
   $"VALUES (@date, @login, @transact)";
command.Parameters.Add("@date", SqlDbType.DateTime).Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
command.Parameters.Add("@login", SqlDbType.NChar).Value = Login;
command.Parameters.Add("@transact", SqlDbType.Text).Value = log;