简体   繁体   English

使用ASPNETDB.MDF添加到c#asp.net中的表

[英]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. 有没有一种方法可以访问我在asp.net 4.0中创建新网页时添加到默认ASPNETDB.MDF数据库中的表。 I have added a table called BuilderTable with 5 columns. 我添加了一个包含5列的名为BuilderTable的表。 Also I need it to increment ID on its own. 我还需要它自己增加ID。 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. 我已经将is identity选项设置为yes,并且标识增量设置为1,因此如何在不向后面的代码中的ID列发送值的情况下使其工作。 Here is said code in c#:(I have it within a switch statement so dont mind the case 1) 这是c#中的代码:(我在switch语句中包含了它,所以不要介意情况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' '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' 即“ BuilderTable”

(You should be using parametrized queries. Look up "Sql Injection Attacks".) (您应该使用参数化查询。查找“ Sql注入攻击”。)

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,,,,,)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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