Inserting rows into a database in ASP.NET

2019-05-31 07:42发布

问题:

I am new to .NET, and I'm can't seem to figure out something that should be simple. I want to insert a row into a table, and initialize it with values that aren't bound to data controls. Specifically, I have a CreateUserWizard control on a page. In the CreatedUser method, I want to insert a row into a databse I created called "users" that contains the Username and the Email address from the CreateUserWizard control, and the date the new user was created, from the DateTime.Now function. There doesn't seem to be a way to set the Parameters in the sqlDataSource control in a way that they can access data that is not bound to data controls. Can anyone explain a way for me to do this?

回答1:

You are on the wrong track - you won't use the sqlDataSource control at all. You'll go for a more direct interaction with the database from code. For example:

SqlConnection conn = new SqlConnection(connString);
SqlCommand cmnd = new SqlCommand("Insert Into Table (P1, P2) Values (@P1, @P2)", conn);
cmnd.Parameters.AddWithValue("@P1", P1Value);
cmnd.Parameters.AddWithValue("@P2", P2Value);
cmnd.ExecuteNonQuery();
conn.Close();

Now, with that all being said, you'll want to learn the SqlCommand and SqlDataReader in some detail (they are pretty straightforward) and then turn your attention to building a Data Access Layer that makes sense to you. You'll be glad that you did.



回答2:

Another option is to set defaults on the database itself, so that you don't need to worry about passing Datetime.now.