问题描述
|
我有一张simpe表:
Users
UserID Guid doesnt allow null
Avatar image allows null
Reputation int allows null
我使用以下语句:
string insertCommand = \"INSERT INTO Users (UserID) VALUES\" +\"\"+ \"(\'\"+UsersIdentityToinsert+\"\')\";
UsersIdentityToinsert(此值为Guid,我检查了它的值,它不为null)。
没有抛出异常。用户一旦按下登录按钮,便将其转移到另一个页面,并插入其记录。
我进行了调试,即执行了该语句。
当我返回到Visual Studio 2010中的服务器资源管理器并单击“刷新”时,“用户”表为空。这是为什么?
连接字符串
<add name=\"YourGuruDB\" connectionString=\"Data Source=DIMA-00AA1DA557;Initial Catalog=model;Integrated Security=True\"/>
我从配置检索到代码:
WebConfigurationManager.ConnectionStrings[\"YourGuruDB\"].ConnectionString;
添加:
public static void InsertUsers(Guid UsersIDentity)
{
sqlConnection sqlConnect = getsqlConnection();
sqlCommand sqlCommand = new sqlCommand(Registerado.insertCommand(UsersIDentity),sqlConnect);//insert command method returns the insert statement described above
try
{
sqlConnect.open();
sqlCommand.ExecuteNonQuery();
}
catch (Exception x)
{
HttpContext.Current.Response.Redirect(\"~/ErrorPage.aspx?Error=\" + WRITE_ERROR);
}
finally
{
sqlConnect.Close();
}
}
解决方法
而不是使用
\"INSERT INTO Users (UserID) VALUES\" +\"\"+ \"(\'\"+UsersIdentityToinsert+\"\')\";
用这个:
\"INSERT INTO Users (UserID) VALUES\" +\"\"+ \"(CONVERT(uniqueidentifier,\'\"+UsersIdentityToinsert+\"\'))\";
而且,您实际上应该使用准备好的Statement而不是连接sql。
那么数据库连接呢?到目前为止,您是否运行过任何成功的语句?尝试一个简单的选择。
, 尝试这个 :
\"INSERT INTO Users (UserID) VALUES (\'\"+UsersIdentityToinsert+\"\')\";
, 有很多事情要检查
您连接到正确的数据库了吗?
执行此SQL语句的代码是否真正起作用。您不显示该代码。我期望某个地方的SqlCommand
对象上有ExecuteNonQuery()
。
您实际上是否打开了与数据库的连接?还是连接字符串仅在配置中而未在代码中的任何地方使用?
另外,您的代码容易受到SQL注入攻击。您应该使用参数化查询来防止这种情况。有关SQL注入攻击的这篇文章将帮助您编写代码。
您还缺少我希望看到的代码。与此类似:
string insertCommand = \"INSERT INTO Users (UserID) VALUES\"
+\"\"+ \"(\'\"+UsersIdentityToinsert+\"\')\";
string cs = WebConfigurationManager.ConnectionStrings[\"YourGuruDB\"].ConnectionString;
SqlConnection conn = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(insertCommand,conn);
conn.Open();
cmd.ExexuteNonQuery();
conn.Close();