StringBuilder sb = new StringBuilder();
sb.Append("DECLARE @ControlPaneliD int");
sb.Append(" SET @ControlPaneliD=(SELECT ControlPanelID");
sb.Append(" FROM ControlPanelID");
sb.Append(开发者_Go百科" WHERE Name=@Name)");
sb.Append("DECLARE @UserName UniqueIdentifier");
sb.Append(" SET @UserName=(SELECT Name");
sb.Append(" FROM UsersID");
sb.Append(" WHERE UsersID=@UserID)");
sb.Append("INSERT INTO dbo.CP_Comments (ControlPanelID,Comments,Commentator)");
sb.Append(" VALUES(@ControlPaneliD,@Comment,@UserName)");
MembershipUser CurrentUser = Membership.GetUser();
Guid id = (Guid)CurrentUser.ProviderUserKey;
string myConnectionString = AllQuestionsPresented.connectionString;
using (SqlConnection conn = new SqlConnection(AllQuestionsPresented.connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
cmd.Parameters.Add("UserID", SqlDbType.UniqueIdentifier).Value = id;
cmd.Parameters.Add("Comment", SqlDbType.NVarChar).Value = TextBox1.Text;
cmd.Parameters.Add("Name", SqlDbType.NVarChar).Value = name; //string variable from my code
cmd.ExecuteNonQuery();
}
I am trying to do two select statements, put their results in their variables and insert their variables plus another variable into another insert statement..
I am not sure if I am doing it right, I would appreciate your help if you gave me some advice and some criticism on what I composed
- In insert statement you inserting 3 parameters into 2 columns.
- I think you should write stored procedure and pass parameters for it. You always "generating" sql code with string builder. And to change some functionality in stored procedure is much easier than find statement in code, change it and rebuild app.
SELECT ControlPanelID FROM ControlPanelID WHERE Name=@Name
andSELECT Name FROM UsersID WHERE UsersID=@UserID
looks strange. Do you really have tables with namesControlPanelID
andUsersID
?
Your method looks OK but it is recommended that you use stored procedure instead of passing query
This is really vulnerable to SQL-injection, especially this part:
cmd.Parameters.Add("Comment", SqlDbType.NVarChar).Value = TextBox1.Text;
This is very, very dangerous. I cannot imagine you haven't heard about this, but just in case, check out this wiki article: http://en.wikipedia.org/wiki/SQL_injection
If you really want/ need to execute raw SQL, always escape the values.
Have you considered using a strongly typed DAL like LINQ2SQL, DataEntities etc?
I would rather suggest putting that code in a stored procedure. Its not a good idea to put that in a string builder and execute it.
精彩评论