开发者

I need help with sql and data relation tables

i building a mini forum site.. and i constructed a few tables.

1) Users 2) 开发者_运维技巧Threads 3) Comments 4) Topics

i build a function that would insert a comment each time a user would submit a comment:

         string saveComment = "INSERT INTO Comments(";
     saveComment += " UsersID, ThreadsID, Date, Comments, CommentResponse";


     saveComment += "Values('" + "','";// no idea what to insert in the UsersID
     saveComment += "" + "','";// no idea what to insert in the ThreadsID

     saveComment += DateTime.Now + "','";
     saveComment += CommenttxtBox.Text + "','";
     saveComment += commentResponseString + "')";

As you can see the fields have UsersID and ThreadID, both connected by a foreign key to the comments table. Now, each time the user submits a comment, i guess i need to insert also to the UsersID field (which is an int in the comments table, and that field increases incrementally by 1 in the Users table). How can i insert a comment, and notify the other table not to increase the UserID by 1. in fact i want it the UserID to stay the same for each user submitting a comment..

How do i do that? i need to insert to a few fields in one table (comments) but keep the other tables informed that it is actually the same user who submitted the comment .

Note: i dont know any vb, only c#, and i use visual studio 2010. asp.net


BTW, the way you are inserting is a security issue, you could get SQL injection ...

Use the system.data.sqlclient.sqlparameters to passe values.


You are creating a very standard normalised structure. Your Users table will be responsible for controlling the UserID values that are generated.

You have two situations to cope with when inserting new comments:

  1. The User exists and is logged in.
  2. The User does not exist and is anonymous.

In the first situation, when you are inserting the comments you will not need to bother looking at the Users table. This assumes you have the UserID already loaded (as the user is logged in).

In the second situation, you will first need to a new row to the Users table and return the UserID that the table generates (assuming you are using an identity column). You can then pass this value to the Comments table.

The following script is an example of addressing the second situation:

DECLARE @userId int

INSERT INTO Users (Username, FirstName)
VALUES ('adamh', 'Adam')

SET @userId = SCOPE_IDENTITY()

INSERT INTO Comments(UserId, ThreadId, Comment)
VALUES (@userId, 1, 'My comment')

If you want to continue with your current coding style, simply concatenate the values into the relevant parts of the string.

However, with such as neatly defined structure as the one you have, I'd advise using something like Entity Framework 4.0, or LINQ to SQL, which cuts a lot of plumbing out once you have defined your structures.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜