繁体   English   中英

使用Asp.Net更新mysql数据库

[英]Update the mysql database using Asp.Net

在这里,我得到了一个使用select Query的Web表单,并显示了一个表单,我需要使用Query来更新它,但我尝试丢失方法。 我无法更新,它只是更新,而是传递旧值而不是新的更改值。

Here is the form 



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Editcar.aspx.cs" MasterPageFile="MasterPage2.master" Inherits ="Editcar" %>
<asp:Content ID="formContent" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">


 <form id="form1" runat="server" class="col-md-10" methode="post" >


    <asp:Table ID="GridView1" class="nav-justified" runat="server" AutoGenerateColumns="false" Height="628px" Width="763px">
        <asp:TableRow>
           <asp:TableCell>
                <h4> Car name:</h4>

           </asp:TableCell>
           <asp:TableCell>
                <asp:TextBox ID="id" runat="server" name="id" Width="301px" Text='<%# Eval("id") %>' Visible="False" CssClass="form-control"></asp:TextBox>
                <asp:TextBox ID="carmake" runat="server" Font-Names="carmake" Width="301px" Text='<%#  Eval("car_make") %>' CssClass="form-control"></asp:TextBox>

           </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
           <asp:TableCell>
                <h4> Car model:</h4>
           </asp:TableCell>
           <asp:TableCell>
                <asp:TextBox ID="carmodel" runat="server" name="carmodel" Text='<%#  Eval("car_model") %>' Width="301px" CssClass="form-control"></asp:TextBox>
           </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
           <asp:TableCell>
                <h4> Price: </h4>
           </asp:TableCell>
           <asp:TableCell>
                <asp:TextBox ID="price"  name="price" runat="server" Width="301px"  CssClass="form-control"></asp:TextBox>
           </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
           <asp:TableCell>
                <h4> Discounted Price If: </h4>
           </asp:TableCell>
           <asp:TableCell>
                <asp:TextBox ID="d_price" name="d_price" runat="server" Width="301px"  CssClass="form-control"/>
           </asp:TableCell></asp:TableRow><asp:TableRow>
           <asp:TableCell> <h4>Car image (Type url)</h4></asp:TableCell><asp:TableCell>
                <asp:TextBox CssClass="form-control" ID="image"  name="image" runat="server" />Just Location
            </asp:TableCell></asp:TableRow><asp:TableRow>
           <asp:TableCell><h4>Avilability</h4></asp:TableCell><asp:TableCell>
                 <asp:TextBox CssClass="form-control" ID="avail"  name="avail" runat="server" />Just Location
           </asp:TableCell></asp:TableRow><asp:TableRow>
           <asp:TableCell><h4>Quantity</h4></asp:TableCell><asp:TableCell>
                 <asp:TextBox CssClass="form-control" ID="quantity"   name="quantity" runat="server" />Just Location
           </asp:TableCell></asp:TableRow><asp:TableRow>
           <asp:TableCell>
                <h4>Long description </h4>
           </asp:TableCell><asp:TableCell>

                <asp:TextBox ID="details" name="details" runat="server" Width="295px"  CssClass="form-control" Height="81px" TextMode="MultiLine"></asp:TextBox>
           </asp:TableCell></asp:TableRow><asp:TableRow>
           <asp:TableCell>
                <h4>Year </h4>
           </asp:TableCell><asp:TableCell>
                <asp:TextBox ID="year" name="year" runat="server" Width="295px"  CssClass="form-control" ></asp:TextBox>
           </asp:TableCell></asp:TableRow><asp:TableRow>
           <asp:TableCell>
                <h4>Special Discounted(0 0r 1) </h4>
           </asp:TableCell><asp:TableCell>
                <asp:TextBox ID="special" name="special"  runat="server" Width="295px"  CssClass="form-control"  ></asp:TextBox>
           </asp:TableCell></asp:TableRow></asp:Table><asp:Button ID="button" OnClick="button_click" runat="server"  Cssclass="btn btn-primary btn-lg btn-block" Text="Update the car" />

   </form>

这里是cs的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Configuration;
using System.Data;
using MySql.Data.MySqlClient;

public partial class Editcar : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

    using (MySqlConnection con = new MySqlConnection(constr))
    {
        var id = Request.QueryString["id"];
        string selectquery = "SELECT * FROM product WHERE id=" + @id;
        MySqlCommand cmd = new MySqlCommand(selectquery);
        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;
        con.Open();
        cmd.ExecuteNonQuery();

        MySqlDataAdapter da = new MySqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);

        foreach (DataRow dr in dt.Rows)

        {
            newid.Text = dr["id"].ToString();
            carmake.Text = dr["car_make"].ToString();
            carmodel.Text = dr["car_model"].ToString();
            price.Text = dr["unitprice"].ToString();
            d_price.Text = dr["discountprice"].ToString();
            image.Text = dr["image"].ToString();
            quantity.Text = dr["quantity"].ToString();
            avail.Text = dr["availability"].ToString();
            details.Text = dr["details"].ToString();
            year.Text = dr["year"].ToString();
            special.Text = dr["special"].ToString();
        }
    }
}

public void button_click(object sender, EventArgs e)
{
    string constor = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    MySqlConnection conn = new MySqlConnection(constor);

    string sql = "Update product SET car_make=@carmake, car_model=@carmodel, UnitPrice=@price, Discountprice=@d_price, image=@image, Quantity=@quantity, availability=@avail, details=@details, year=@year, special=@special  WHERE id= @id";
    var cmd = new MySqlCommand(sql, conn);

    conn.Open();
    cmd.Parameters.AddWithValue("@id", newid.Text);
    cmd.Parameters.AddWithValue("@carmake", carmake.Text);
    cmd.Parameters.AddWithValue("@carmodel", carmodel.Text);
    cmd.Parameters.AddWithValue("@price", price.Text);
    cmd.Parameters.AddWithValue("@d_price", d_price.Text); // put zero if no discount
    cmd.Parameters.AddWithValue("@image", image.Text);
    cmd.Parameters.AddWithValue("@quantity", quantity.Text);
    cmd.Parameters.AddWithValue("@avail", avail.Text);
    cmd.Parameters.AddWithValue("@details", details.Text);
    cmd.Parameters.AddWithValue("@year", year.Text);
    cmd.Parameters.AddWithValue("@special", special.Text);
    cmd.Parameters.AddWithValue("@id", newid.Text);

    var ex = cmd.ExecuteNonQuery();

    if (ex == 1)
    {
        Response.Redirect("AdminList.aspx");
    }
    else
    {
        Response.Write("Error");
    }
    conn.Close();
}
}

只是更新而未获得表值

我也用过ajax,它没有用

您没有将参数与MySQL命令对象相关联。 您声明参数并填充它们,但是它们不与命令关联,因此它们不会传递给数据库。

您可以使用以下任一方法:

cmd.Parameters.Add(param[0]); 

例如,对每个参数重复此操作。

或使用AddWithValue方法更简洁:

cmd.Parameters.AddWithValue("@carmake", carmake); 

这只是指定名称和值,并让.NET推断数据类型。 再次,对每个参数重复。 然后,您可以摆脱数组和new MySqlParameter所有声明。

最后,您的SQL字符串应如下所示:

"Update product SET car_make = @carmake, car_model= @carmodel, " //...etc

即不是" + @carmake + ", -只是连接表单字段的值,这些字段恰好具有与SQL参数完全相同的名称。

这是CS文件的正确方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Configuration;
using System.Data;
using MySql.Data.MySqlClient;

public partial class Editcar : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

            using (MySqlConnection con = new MySqlConnection(constr))
            {
                var id = Request.QueryString["id"];

                string selectquery = "SELECT * FROM product WHERE id=" + @id;

                MySqlCommand cmmd = new MySqlCommand(selectquery);
                cmmd.Connection = con;
                cmmd.CommandType = CommandType.Text;

                con.Open();
                cmmd.ExecuteNonQuery();

                MySqlDataAdapter da = new MySqlDataAdapter(cmmd);
                DataTable dt = new DataTable();
                da.Fill(dt);

                foreach (DataRow dr in dt.Rows)
                {
                    newid.Text = dr["id"].ToString();
                    carmake.Text = dr["car_make"].ToString();
                    carmodel.Text = dr["car_model"].ToString();
                    price.Text = dr["unitprice"].ToString();
                    d_price.Text = dr["discountprice"].ToString();
                    image.Text = dr["image"].ToString();
                    qnty.Text = dr["quantity"].ToString();
                    avbl.Text = dr["availability"].ToString();
                    details.Text = dr["details"].ToString();
                    year.Text = dr["year"].ToString();
                    special.Text = dr["special"].ToString();
               }
         }
    }
}

public void button_click(object sender, EventArgs e)
{
        string constor = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    MySqlConnection conn = new MySqlConnection(constor);

    string sql = "Update product SET car_make=@carmake, car_model=@carmodel, UnitPrice=@price, Discountprice=@d_price, image=@image, Quantity=@quantity, availability=@avail, details=@details, year=@year, special=@special  WHERE id= @id";

    var cmd = new MySqlCommand(sql, conn);
    conn.Open();
    cmd.Parameters.AddWithValue("@carmake", carmake.Text);
    cmd.Parameters.AddWithValue("@carmodel", carmodel.Text);
    cmd.Parameters.AddWithValue("@price", price.Text);
    cmd.Parameters.AddWithValue("@d_price", d_price.Text); // put zero if no discount
    cmd.Parameters.AddWithValue("@image", image.Text);
    cmd.Parameters.AddWithValue("@quantity", qnty.Text);
    cmd.Parameters.AddWithValue("@avail", avbl.Text);
    cmd.Parameters.AddWithValue("@details", details.Text);
    cmd.Parameters.AddWithValue("@year", year.Text);
    cmd.Parameters.AddWithValue("@special", special.Text);
    cmd.Parameters.AddWithValue("@id", newid.Text);

    var ex = cmd.ExecuteNonQuery();

    if (ex == 1)
    {
        Response.Redirect("AdminList.aspx");
    }
    else
    {
        Response.Write("Error");
    }
    conn.Close();
    }
  }

在这里,我使用了if (!this.IsPostBack)以便阻止传导的Page_load代码影响Button_Click数据。

这是我用于从表单添加(INSERT)的方法

using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;

public partial class Admingroup_Addcar : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    private void ExecuteInsert(string id, string carmake, string carmodel, string price, string d_price, string image,
        string quantity, string details, string year, string special)
    {
        var constr = "SERVER=localhost;" +
                     "DATABASE=carsstore;" +
                     "UID=root;" +
                     "PASSWORD=;";

        var conn = new MySqlConnection(constr);

        var avail = 1;

        var sql =
            "INSERT INTO product (id, car_make, car_model, UnitPrice, Discountprice, image, Quantity, availability, details, year, special) VALUES ('" +
            @id + "','" + @carmake + "','" + @carmodel + "','" + @price + "','" + @d_price + "','" + @image + "','" +
            @quantity + "','" + @avail + "','" + @details + "','" + @year + "','" + @special + "');";

        try
        {
            conn.Open();

            var cmd = new MySqlCommand(sql, conn);
            var param = new MySqlParameter[11];

            param[0] = new MySqlParameter("@id", MySqlDbType.VarChar, 4);
            param[1] = new MySqlParameter("@carmake", MySqlDbType.VarChar, 100);
            param[2] = new MySqlParameter("@carmodel", MySqlDbType.VarChar, 100);
            param[3] = new MySqlParameter("@price", MySqlDbType.VarChar, 100);
            param[4] = new MySqlParameter("@d_price", MySqlDbType.VarChar, 100); // put zero if no discount
            param[5] = new MySqlParameter("@image", MySqlDbType.VarChar, 300);
            param[6] = new MySqlParameter("@quantity", MySqlDbType.VarChar, 300);
            param[7] = new MySqlParameter("@avail", MySqlDbType.VarChar, 2);
            param[8] = new MySqlParameter("@details", MySqlDbType.VarChar, 2000);
            param[9] = new MySqlParameter("@year", MySqlDbType.VarChar, 4);
            param[10] = new MySqlParameter("@special", MySqlDbType.VarChar, 2);

            param[0].Value = id;
            param[1].Value = carmake;
            param[2].Value = carmodel;
            param[3].Value = price;
            param[4].Value = d_price;
            param[5].Value = image;
            param[6].Value = quantity;
            param[7].Value = avail;
            param[8].Value = details;
            param[9].Value = year;
            param[10].Value = special;

            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
        }
        catch (MySqlException ex)
        {
            var msg = "Insert Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            conn.Close();
        }
    }

    protected void button_click(object sender, EventArgs e)
    {
        if (price.Text != d_price.Text)
        {
            //call the method to execute insert to the database
            ExecuteInsert(id.Text, carmake.Text,
                carmodel.Text,
                price.Text,
                d_price.Text,
                image.Text,
                quantity.SelectedItem.Text,
                details.Text,
                year.Text,
                special.Text
                );
            Response.Write("Record was successfully added!");
            ClearControls(Page);
        }
        else
        {
            Response.Write("Record Error");
            d_price.Focus();
        }
    }

    public static void ClearControls(Control Parent)
    {
        if (Parent is TextBox)
        {
            (Parent as TextBox).Text = string.Empty;
        }
        else
        {
            foreach (Control c in Parent.Controls)
                ClearControls(c);
        }
    }
} 

暂无
暂无

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

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