No data is inserted into my table
I have a simpe table:
Users
UserID Guid doesnt allow null
Avatar image allows null
Reputation int allows null
I used the following statement:
string insertCommand = "INSERT INTO Users (UserID) VALUES" +""+ "('"+UsersIdentityToinsert+"')";
UsersIdentityToinsert(this value is a Guid, I checked its value, it isn't null).
There were no exceptions thrown. As soon as the user presses the login button, he is transfered to another page, and his record is inserted. I followed with the debugging that that statement is executed.
When I return to my server explore开发者_如何学Cr in Visual Studio 2010 and click refresh the Users table is empty. Why is that?
Connection string
<add name="YourGuruDB" connectionString="Data Source=DIMA-00AA1DA557;Initial Catalog=model;Integrated Security=True"/>
i retrieve it from config into the code:
WebConfigurationManager.ConnectionStrings["YourGuruDB"].ConnectionString;
Added:
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();
}
}
Instead of using
"INSERT INTO Users (UserID) VALUES" +""+ "('"+UsersIdentityToinsert+"')";
use this:
"INSERT INTO Users (UserID) VALUES" +""+ "(CONVERT(uniqueidentifier, '"+UsersIdentityToinsert+"'))";
And you really should use a prepared Statement instead of concatenating the sql.
What about the DB-connection? Did you run any successfull statements so far? Try a simple select.
try this :
"INSERT INTO Users (UserID) VALUES ('"+UsersIdentityToinsert+"')";
There are a number of things to check
- Are you connected to the right database?
- Is the code that executes this SQL Statement actually working. You don't show that code. I'd be expecting a
ExecuteNonQuery()
on aSqlCommand
object somewhere. - Do you actually open a connection to a database? Or is the connection string just in the config without being used anywhere in your code?
Also, your code is susceptible to a SQL Injection attack. You should use a parameterised query to prevent that. This article on SQL Injection Attacks will help you with how to write that.
You also have missing code which I'd expect to see. Something along the lines of this:
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();
精彩评论