Latest update Android YouTube

MySQL with ASP.NET Web Forms (C#) - IndianTechnoEra

Learn how to connect MySQL with ASP.NET Web Forms using C#. Step-by-step tutorial with code examples, connector installation, connection strings.

🛠️ How to Connect MySQL with ASP.NET Web Forms (C#) – Full Guide

Integrating MySQL with your ASP.NET Web Forms application is a great way to use an open-source, robust database system. In this guide, we’ll walk through everything from setting up the connection to executing queries using MySql.Data.

 MySQL with ASP.NET Web Forms (C#) - IndianTechnoEra

1. 🔧 Prerequisites

Before we begin, make sure you have:

  • MySQL Server installed locally or remotely
  • Visual Studio with .NET Web Forms support
  • A MySQL database created
  • Basic knowledge of C# and Web Forms

2. 📦 Installing MySQL Connector

Use NuGet Package Manager to install the MySQL connector.

Option 1: GUI

  • Right-click on your project > Manage NuGet Packages
  • Search for MySql.Data and install it

Option 2: Console

Install-Package MySql.Data

3. ⚙️ Updating Web.config

Add your connection string:

<connectionStrings>
  <add name="DefaultConnection"
       connectionString="Server=localhost;Database=your_db;Uid=your_user;Pwd=your_password;"
       providerName="MySql.Data.MySqlClient" />
</connectionStrings>

Replace: your_db, your_user, your_password with actual credentials.

4. 🧑‍💻 Creating a User Model

public class UserModel
{
    public string UserName { get; set; }
    public string Password { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
}

5. 💾 Inserting Data into MySQL

Registration Code (btnRegister_Click):

protected void btnRegister_Click(object sender, EventArgs e)
{
    UserModel user = new UserModel
    {
        UserName = UserName.Text,
        Password = Password.Text,
        Email = Email.Text,
        Phone = Phone.Text
    };

    string connStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

    using (MySqlConnection conn = new MySqlConnection(connStr))
    {
        conn.Open();
        string query = "INSERT INTO users (username, password, email, phone) VALUES (@username, @password, @email, @phone)";
        using (MySqlCommand cmd = new MySqlCommand(query, conn))
        {
            cmd.Parameters.AddWithValue("@username", user.UserName);
            cmd.Parameters.AddWithValue("@password", user.Password);
            cmd.Parameters.AddWithValue("@email", user.Email);
            cmd.Parameters.AddWithValue("@phone", user.Phone);
            cmd.ExecuteNonQuery();
        }
    }
}

6. 📖 Reading Data from MySQL (Login)

protected void btnLogin_Click(object sender, EventArgs e)
{
    string username = LoginUserName.Text;
    string password = LoginPassword.Text;

    string connStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

    using (MySqlConnection conn = new MySqlConnection(connStr))
    {
        conn.Open();
        string query = "SELECT * FROM users WHERE username = @username AND password = @password";
        using (MySqlCommand cmd = new MySqlCommand(query, conn))
        {
            cmd.Parameters.AddWithValue("@username", username);
            cmd.Parameters.AddWithValue("@password", password);
            using (MySqlDataReader reader = cmd.ExecuteReader())
            {
                if (reader.Read())
                {
                    Session["UserName"] = reader["username"].ToString();
                    Response.Redirect("~/Pages/Dashboard.aspx");
                }
                else
                {
                    ErrorMessage.Text = "Invalid credentials.";
                }
            }
        }
    }
}

7. ✅ Best Practices

  • 🔒 Always hash and salt passwords (e.g., SHA256 or bcrypt)
  • 🧹 Use using statements for proper disposal
  • 📦 Separate DB logic into a DAL (Data Access Layer)
  • 📋 Validate input both client-side and server-side
  • 🛡️ Never store production credentials in plain text

8. 🔚 Conclusion

With this setup, you’ve learned how to:

  • Install and connect to MySQL from .NET
  • Perform INSERT and SELECT operations
  • Follow security and structure best practices

Now you can build ASP.NET apps with the power and flexibility of MySQL!

إرسال تعليق

Feel free to ask your query...
Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.