Data not getting inserted into mysql database in asp.net c# web application

Akash Desai :

I'm trying to insert simple data in mysql database on a button click but whenever I try to do so, the button click is processed but the data is not getting inserted and also there are no exceptions or errors. I have the database stored in my localhost with exact same table name and column name yet it is creating the problem. Don't know the issue seems to be.

testing.aspx file

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="testing.aspx.cs" Inherits="CricketAnalysis2.testing" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
        </div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <p>
            <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
        </p>
    </form>
</body>
</html>

testing.aspx.cs file

using System;
using MySql.Data.MySqlClient;
using System.Data;

namespace CricketAnalysis2
{
    public partial class testing : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            MySqlConnection con = new MySqlConnection(@"Data Source=localhost;port=3306;Initial Catalog=cricdb;User Id=root;password=''");
            con.Open();
            MySqlCommand cmd1 = con.CreateCommand();
            cmd1.CommandType = CommandType.Text;
            cmd1.CommandText = "INSERT INTO drug VALUES ('"+TextBox1.Text+"')";
            con.Close();
        }
    }
}
Izzy :

The issue is you're not executing the command. You need to call ExecuteNonQuery() method so:

cmd1.ExecuteNonQuery();

Furthermore, your query is currently open to sql injection, to avoid that you should use paramertised queries and also make use of using block to ensure the object is disposed correctly.

var connectionString = "Data Source=localhost;port=3306;Initial Catalog=cricdb;User Id=root;password=''\"";
var query = "INSERT INTO DRUG VALUES(@ParameterName)";
using (var con = new MySqlConnection(connectionString))
{
  using (var cmd = new MySqlCommand(query, con))
  {
     cmd.Parameters.Add("@ParameterName", MySqlDbType.VarChar).Value = TextBox1.Text;

     con.Open();
     cmd.ExecuteNonQuery();
   }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=386639&siteId=1