简体   繁体   English

在C#中添加/访问ASP.Net中的数据库

[英]Adding to/Accessing a database in ASP.Net in C#

I have been working on this school assignment and have gotten to a point at which I have been stuck for a few days now. 我一直在从事这项学校作业,现在已经陷入困境了几天。 My ASP.net web page is supposed to allow the user to create an account and login. 我的ASP.net网页应该允许用户创建帐户并登录。 However, no matter how many times I fill in the Create Account form, it doesn't seem to get added to the database. 但是,无论我填写创建帐户表单有多少次,它似乎都不会添加到数据库中。

Here is my User class, which holds the createAccount Method 这是我的User类,其中包含createAccount方法

public class Userr
    {




        //Constructor for the Account Creation method(createAccount)
        public string createAccount(string strFname, string strLname, string strUname, string address, string city, string state, string phone, string zip, string email,string password)
        {
            string i="";
            string storedProcText = ("INSERT INTO User Values('@ID," +strUname +"','"+strFname +"','"+ strLname +"','"+address +"','"+city +"','"+state+"','"+zip+"','"+phone+"','"+ email +"','"+ password );

                ArrayList parms = null;
            DataAccess dataAccess = new DataAccess();
            int result = dataAccess.insertUpdateData(parms,storedProcText );

           i  =result.ToString();
            return i;

        }

        public string Login(string strUsername, string strPassword)
        {
            DataAccess objDA = new DataAccess();
            int result = objDA.LoginUser(strUsername, strPassword);
        }

    }

Here is my method for updating(stored in the dataAccess object/class 这是我的更新方法(存储在dataAccess对象/类中

 //Constructor for the update method
        public int insertUpdateData(ArrayList items, String strProcedureName)
        {
            int i = 0;

            string strConn = WebConfigurationManager.ConnectionStrings["TicketsConnectionString"].ConnectionString;
            SqlConnection myConnection = new SqlConnection(strConn);

            string sqlText = strProcedureName;
            SqlCommand myCommand = new SqlCommand(sqlText);
            myCommand.Connection = myConnection;
            myCommand.CommandType = CommandType.StoredProcedure;

            try
            {
                    using (myConnection)
                {
                    myConnection.Open();
                    i = myCommand.ExecuteNonQuery();

                    //grdData.DataSource = myReader;
                   // grdData.DataBind();
                }

            } 
            catch (Exception err)
            {



            } 

            return i;
        }

The User table contains the follwing fields in order: ID, UserID, FirstName,LastName, Address, City, State, Zip,Phone,EmailAddress,Password 用户表按顺序包含以下字段:ID,UserID,FirstName,LastName,Address,City,State,Zip,Phone,EmailAddress,Password

Is my SQL statement wrong, or what? 我的SQL语句是错误的还是什么? I am at the end of my rope here. 我在这里尽头。

So, to start from the beginning, have you stepped through this code with the debugger and determined if it's throwing an exception or returning zero rows modified? 因此,从头开始,您是否已使用调试器逐步执行了此代码,并确定它是引发异常还是返回已修改的零行?

The most worrisome thing is the insertion of the @ID column. 最令人担忧的是@ID列的插入。 If this is an Identity column you shouldn't be inserting this value. 如果这是“身份”列,则不应插入该值。 If it's not, I don't see you assigning a value to it anywhere. 如果不是,我看不到您在任何地方为其分配值。

EDIT: 编辑:

So as has been mentioned by others here you have some structural issues in you query. 因此,正如其他人在这里提到的那样,您在查询中遇到了一些结构性问题。

I took your code and threw it in a quick project and here's what your statement looks like. 我将您的代码放入一个快速项目中,这就是您的陈述的样子。

INSERT INTO User Values('@ID,UserName','FirstName','LastName','123 Some Street','SomeTown','State','54555','555-444-3333','email@email.com','ITS_A_SECRET!

Notice the end of the query. 注意查询结束。 The password field isn't escaped with a closing ' and the param list is not closed with a closing bracket. 密码字段不能以'结束转义,并且参数列表也不会以括号引起来。

QueryProblem

A second problem is that @Id field. 第二个问题是@Id字段。 Is your column in the database an identity field? 您在数据库中的列是一个身份字段吗? (It should be) If so, just remove that. (应该是)如果是这样,请将其删除。

Now, here's the real kicker. 现在,这才是真正的踢腿。 Is your table name User? 您的表名是User吗? That's a reserved word in SQL server so you'll get errors in your query as is. 这是SQL Server中的保留字,因此您将在查询中直接得到错误。 Format you query like the following and it will work. 像下面这样格式化查询,它将起作用。

string storedProcText = ("INSERT INTO [dbo].[User] Values('" + strUname + "','" + strFname + "','" + strLname + "','" + address + "','" + city + "','" + state + "','" + zip + "','" + phone + "','" + email + "','" + password + "')");

RightSQL

The other issue, as mentioned is that you have the command type set to Stored Procedure when you are not using one. 如前所述,另一个问题是您不使用命令时将命令类型设置为“存储过程”。

Modifying you command type to text: 将命令类型修改为文本:

myCommand.CommandType = CommandType.Text;

NoSProc

After I made these modifications and ran your code I ended up with a record in the database. 完成这些修改并运行您的代码后,我最终在数据库中获得了一条记录。

结果

The most important thing to check right now is that ID field. 现在最要检查的是该ID字段。 Is it an identity column? 是标识列吗? Make sure it is and then remove it from your statement. 确保它是正确的,然后将其从您的对帐单中删除。

So, off the bat, I see a few issues: 因此,即时来看,我看到了一些问题:

  1. You set your myCommand.CommandType = CommandType.StoredProcedure but, the syntax you provided is not a stored proc. 您设置myCommand.CommandType = CommandType.StoredProcedure但是提供的语法不是存储的proc。 A stored proc would take a name value list of params, which is null in your case. 存储的proc将采用参数的名称值列表,在您的情况下为null。

  2. Lets say you didn't mean to use stored procs, in which case, your sql syntax is incorrect. 可以说您并不是要使用存储的proc,在这种情况下,您的sql语法不正确。 You don't need the @ID parameter, unless you are passing it in (in which case, you didn't set it). 您不需要@ID参数,除非传入它(在这种情况下,您没有设置它)。 It should be something like this (without knowing the structure of your table): 它应该是这样的(不知道表的结构):

string storedProcText = ("INSERT INTO User Values("'" +strUname +"','"+strFname +"','"+ strLname +"','" + address +"','"+city +"','"+state+"','"+zip+"','"+phone+"','"+ email +"','"+ password + "'");

This is given that the values you are inserting matches your table exactly. 假设您要插入的值与表完全匹配。 If not, you will need to specify the table field names in your query as well, like so: 如果没有,那么您还需要在查询中指定表字段名称,如下所示:

string storedProcText = ("INSERT INTO User(username, firstName, lastName, field4, field5, field6) Values("'" +strUname +"','"+strFname +"','"+ strLname +"','" + address +"','"+city +"','"+state+"','"+zip+"','"+phone+"','"+ email +"','"+ password + "'");

The way to do this using stored procs is this: 使用存储的proc来做到这一点的方法是:


 SqlParameter[] parameters = { 
                new SqlParameter("@param1", SqlDbType.NVarChar, 50),
                new SqlParameter("@param2", SqlDbType.VarChar, 100),
                new SqlParameter("@param3", SqlDbType.VarChar, 100),
                new SqlParameter("@param4", SqlDbType.VarChar, 100),
                new SqlParameter("@param5", SqlDbType.VarChar, 100),
                new SqlParameter("@param6", SqlDbType.VarChar, 100)
            };
            parameters[0].Value = strFname;
            parameters[1].Value = strLname;
            .........
            .........
            [all the parameters you need]

You need to create a stored proc, also (obviously) 您还需要创建一个存储的proc,(显然)

And then you call your dataaccess layer just like you are doing. 然后,就像执行操作一样,调用数据访问层。



Steps for making this work: 1) Don't catch and swallow every exception. 进行此工作的步骤:1)不要捕获并吞下所有异常。 The exception will tell you what you are doing wrong here. 异常会告诉您您在这里做错了什么。 2) As Caspar Kleijne points out, you need to put the password in quotes. 2)正如Caspar Kleijne指出的那样,您需要将密码放在引号中。 3) As I point out, you need to add a parenthesis. 3)正如我所指出的,您需要添加一个括号。 4) You should also use parameterized SQL queries 5) You probably shouldn't be passing the ID, 4)您还应该使用参数化的SQL查询5)您可能不应该传递ID,

Here's the corrected SQL string for #2 and #3: 这是#2和#3的更正后的SQL字符串:

string storedProcText = ("INSERT INTO User Values('@ID," 
                         +strUname +"','"+strFname +"','"
                         + strLname +"','"+address +"','"
                         +city +"','"+state+"','"
                         +zip+"','"+phone+"','"
                         + email +"','"+ password 
                         +"')" );

It'll take some refactoring to use parameterized queries, and this is a homework project, so I'll leave that as an exercise for you. 使用参数化查询将需要一些重构,这是一个家庭作业项目,因此我将其留给您练习。

Please Comment out this statement: 请注释以下语句:

myCommand.CommandType = CommandType.StoredProcedure’;

You can use a sql script directly. 您可以直接使用sql脚本。

In the insert you are trying to insert @ID which first of all most likely would be an identity column, and unless you set IDENTITY_INSERT ON on that table, will throw an exception, second, even if it was not an identity column, you are not providing the parameter definition for the @ID parameter to the command. 在插入操作中,您尝试插入@ID,它最有可能首先是一个身份列,并且除非您在该表上将IDENTITY_INSERT设置为ON,否则将抛出一个异常(第二个),即使它不是身份列也是如此。没有为命令的@ID参数提供参数定义。 Try removing @ID from the insert statement, and pass in everything else, but ID. 尝试从插入语句中删除@ID,然后传入除ID外的所有内容。 As a side note, your SQL Statement is prone to SQL Injection attacks since you're concatenating sql command string and values provided by user into one string. 附带说明一下,由于将SQL命令字符串和用户提供的值连接为一个字符串,因此SQL语句容易受到SQL注入攻击。 I would recommend using parameters instead the actual values and then adding parameters to the sql command later. 我建议使用参数代替实际值,然后再将参数添加到sql命令。

I cannot post everything as a comment , but can you do one thing.. 我不能将所有内容都发表为评论,但是您可以做一件事。

put a break point and take the contents of this string 放置一个断点并获取此字符串的内容

string storedProcText = ("INSERT INTO User Values('@ID," +strUname +"','"+strFname +"','"+ strLname +"','"+address +"','"+city +"','"+state+"','"+zip+"','"+phone+"','"+ email +"','"+ password );

and paste the value of storeProcText directly in the database and see if it can successfuly run and create a record for you. 并将storeProcText的值直接粘贴到数据库中,看看它是否可以成功运行并为您创建一条记录。

break and debug should fix your problem 中断并调试应该可以解决您的问题

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

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