我有一个无密钥表(这不是我的手工),我正在尝试使用原始sql插入数据行。我确实尝试映射存储过程但是我遇到了与日期相同的问题。
internal bool InsertSession(Guid UserID, DateTime LastActivityDate, string SessionID)
{
string s = "INSERT INTO aspnet_Custom_UserSessionActivity VALUES (" + "'" + UserID.ToString() + "'" + " ," + LastActivityDate.ToString("yyyy-MM-dd HH:mm:ss") + "," + "'" + SessionID.ToString() + "')";
try
{
using (ALFDataContext)
{
ALFDataContext.Database.ExecuteSqlCommand(s);
ALFDataContext.SaveChanges();
return true;
}
}
catch (Exception ex)
{
return false;
}
}
这是字符串包含的内容:
INSERT INTO aspnet_Custom_UserSessionActivity VALUES ('f4da4c0b-d94e-4f9c-84ef-c82fa442bbc1' ,2014-02-04 09:48:43,'wj4gesi3bdqytflifnzyqx2c')
这是错误:
Incorrect syntax near '09'.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Objects.ObjectContext.ExecuteStoreCommand(String commandText, Object[] parameters)
at System.Data.Entity.Internal.InternalContext.ExecuteSqlCommand(String sql, Object[] parameters)
at System.Data.Entity.Database.ExecuteSqlCommand(String sql, Object[] parameters)
at MembershipProvider.DataAccess.Repository.InsertSession(Guid UserID, DateTime LastActivityDate, String SessionID) in c:\Users\nickgowdy\Documents\Visual Studio 2012\Projects\ALF source code\ALF\branches\Nick's Branch\MembershipProvider\DataAccess\Repository.cs:line 149
我假设我的日期格式错误但我看不到错误。
有没有人有解决这个问题的建议?
答案 0 :(得分:0)
不要,在任何情况下,使用字符串连接将参数插入查询中!
通过构建动态SQL查询,您只需将自己打开到SQL Injection。
使用Entity Framework避免SQL注入非常简单:
internal bool InsertSession(Guid UserID, DateTime LastActivityDate, string SessionID)
{
try
{
using (ALFDataContext)
{
string s = "INSERT INTO aspnet_Custom_UserSessionActivity VALUES ({0}, {1}, {2})";
ALFDataContext.Database.ExecuteSqlCommand(s, UserID, LastActivityDate, SessionID);
// No need to call SaveChanges here.
return true;
}
}
catch (Exception ex)
{
return false;
}
}
ExecuteSqlCommand
方法会自动创建参数化查询,并使用正确的参数名称替换字符串中的{0}
,{1}
和{2}
标记。