繁体   English   中英

使用C#从Visual Studio将数据插入Access数据库中

[英]Inserting Data in an Access Database from Visual Studio using C#

当我尝试使用C#从Visual stutio将数据插入Acess数据库时,我不断收到此错误“ System.Data.OleDb.OleDbException:INSERT INTO语句中的语法错误”。

受保护的无效Button1_Click1(对象发送者,EventArgs e){

        Guid newGUID = Guid.NewGuid();

        OleDbConnection conn = new OleDbConnection(" Provider = Microsoft.ACE.OLEDB.12.0;" + "Data Source = " + Server.MapPath("App_Data/Group.accdb"));

    OleDbCommand command = new OleDbCommand ("INSERT INTO [User] ( [Userid], [UserName], [Password], [Email], [Country], [CartID], [Address] ) VALUES (@Uname,@password,@email,@country,@address,@userid,@cartID)", conn);

    conn.Open();
                command.Parameters.AddWithValue("@userid", Convert.ToString(newGUID));
                command.Parameters.AddWithValue("@Uname", username.Text);
                command.Parameters.AddWithValue("@password", username.Text);
                command.Parameters.AddWithValue("@email", email.Text);
                command.Parameters.AddWithValue("@country", DropDownList1.SelectedItem.ToString());
                command.Parameters.AddWithValue("@cartID", Convert.ToString(newGUID));
                command.Parameters.AddWithValue("@address", address.Text); 
                command.ExecuteNonQuery();
    conn.Close();
            Response.Redirect("Login.aspx");
            Response.Write("Registration is successful");    

}

用户是保留关键字。 您需要像对字段一样将其括在方括号之间

但是,您的代码有一个更严重的错误。
您的参数占位符相对于字段名称的顺序不正确。 因此,您需要修复查询,然后记住在OleDb中,参数不是通过名称识别的,而是通过位置识别的。 因此,将参数添加到集合的代码应遵循您要检索参数值的顺序

OleDbCommand command = new OleDbCommand (@"INSERT INTO [User] 
     ( [Userid], [UserName], [Password], [Email], 
       [Country], [CartID], [Address] ) VALUES 
     ( @userid, @Uname, @password,@email,
       @country,@cartID, @address)", conn);

conn.Open();
command.Parameters.AddWithValue("@userid", address.Text);
command.Parameters.AddWithValue("@Uname", username.Text);
command.Parameters.AddWithValue("@password", username.Text);
command.Parameters.AddWithValue("@email", email.Text);
command.Parameters.AddWithValue("@country",DropDownList1.SelectedItem.ToString());
command.Parameters.AddWithValue("@cartID", address.Text);
command.Parameters.AddWithValue("@address", address.Text);
command.ExecuteNonQuery();

顺便说一句,您正在将用户名文本框传递到“用户名”字段以及“用户ID和密码”。 这似乎不太可能(地址文本框也是如此)

最后,使用字符串设置字段cartID和UserID的值似乎也是错误的。 方法AddWithValue无法知道将由参数更新的字段的DataType是什么。 因此,它将基于值的数据类型创建一个参数。 在您的情况下,address.Text和username.Text是字符串,但是如果数据库字段期望整数,则会发生错误。
如果是这种情况,则应确保您有一个整数并使用

command.Parameters.AddWithValue("@userid", Convert.ToInt32(address.Text));
command.Parameters.AddWithValue("@cartID", Convert.ToInt32(address.Text));

无论如何,最好使用正确的Add方法

command.Parameters.Add("@userid", OleDbType.Integer).Value = Convert.ToInt32(address.Text));

暂无
暂无

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

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