简体   繁体   中英

Inserting rows into a database in ASP.NET

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?

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.

另一种选择是在数据库本身上设置默认值,这样您就不必担心传递Datetime.now了。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM