简体   繁体   中英

Add to a table in the c# asp.net using the ASPNETDB.MDF

Is there a way to access a table that I have added to the default ASPNETDB.MDF database that is given to you when you create a new web page in asp.net 4.0. I have added a table called BuilderTable with 5 columns. Also I need it to increment ID on its own. I have set the is identity option to yes and the identity increment to 1 so how can I get it to work without sending it a value for the ID column in my code behind. Here is said code in c#:(I have it within a switch statement so dont mind the case 1)

     case "1":
            if (Roles.IsUserInRole(usr.UserName, "Builder") == false)//if the user is not already in the builder role then add them
            {
                Roles.AddUserToRole(usr.UserName, "Builder");//here we add the user into the builder role

                string connection = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
                SqlConnection conn = null;
                conn = new SqlConnection(connection);
                conn.Open();

                using (SqlCommand cmd = new SqlCommand())
                {
                    int nothing = 0;
                    string query = String.Format("INSERT INTO 'BuilderTable' VALUES('{0}', '{1}', '{2}', '{3}', '{4}')", nothing, p.fName, p.lName, p.Address, usr.Email);
                    cmd.Connection = conn;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = query;
                    cmd.ExecuteNonQuery();
                }
            }
            break;

This code results in the error:

Incorrect syntax near 'BuilderTable'

Thanks in advance!

EDIT Thought I should clarify I have this declared elsewhere in the code

      string userName = Request.QueryString["user"];
    MembershipUser usr = Membership.GetUser(userName);
    ProfileCommon p = Profile.GetProfile(usr.UserName);

You need to take away the single quotes from around the table name. Ie 'BuilderTable'

(You should be using parametrized queries. Look up "Sql Injection Attacks".)

Your identity error is due to you trying to insert values into the identity field. You should insert values by specifying the fields.

 INSERT INTO BLAH (Fields,,,,) VALUES(Values,,,,,)

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