使用SQL Server中的其他值捕获SQL INSERT语句

时间:2016-11-30 14:06:42

标签: sql sql-server vb.net

我的vb.net应用程序中有一个INSERT语句。一路走来......

 SQL = " Insert into tableA (Value1, Value2, Value3) Values (Mark1, City2, State3) "

我尝试做的是将其传递给实际插入SQL语句的函数。我试图在LOG表中插入此sql语句的副本。

 Public Function (InsertSQL as String) As Boolean
 nSql = "INSERT INTO tblSQLLOG ( InsertSQL, Date, User) VALUES ( "
 nSql += "'" & InsertSQL + "', "
 nSql += "'" & Now() & "', "
 nSql += CStr(userName) + ") "

 cmd = New SqlCommand(nSql, conn)
 End Function

所以现在,如果我检查我的nSQL,它看起来像....

Insert into tblSQLLOG (insert sql, date,user) values ('insert Insert into tableA (Value1, Value2, Value3) Values ('Mark1', 'City2', 'State3')','11/30/2016 8:46:41 AM', 'Bobby')

在此插入声明中,我发现了Value1附近的错误 - 我不知道我做错了什么。一切看起来都很好。

2 个答案:

答案 0 :(得分:3)

你正在做一件大事,那就是你没有使用参数。

Public Function FuncName (InsertSQL as String) As Boolean
 nSql = <sql>INSERT INTO tblSQLLOG 
   ( InsertSQL, [Date], [User]) 
   VALUES 
   ( @InsertSQL, @Date, @User)
 </sql>

 cmd = New SqlCommand(nSql, conn)
 cmd.Parameters.AddWithValue("@InsertSQL", InsertSQL)
 cmd.Parameters.AddWithValue("@Date", DateTime.Now)
 cmd.Parameters.AddWithValue("@User", CStr(userName))

 ' then what? you would use cmd and return true or false

 End Function

PS:还要检查SQL Server中的审核。

答案 1 :(得分:-1)

是的,您应该使用参数。那说问题是你在字符串中有单引号。注意InsertSQL的Replace()

Public Function (InsertSQL as String) As Boolean
 nSql = "INSERT INTO tblSQLLOG ( InsertSQL, Date, User) VALUES ( "
 nSql += "'" & Replace(InsertSQL,"'","''") + "', "
 nSql += "'" & Now() & "', "
 nSql += CStr(userName) + ") "

 cmd = New SqlCommand(nSql, conn)
 End Function