1633367280
この記事では、ASP.NET WebアプリケーションからMySQLデータベースにデータの選択、更新、および削除を挿入する方法について説明します。
それでは、次の手順に進みましょう。
次に、MySQLAdminページを開き、[Create A New Table]-> [View]-> [Table Structure for Table`student`]を選択します。
CREATE TABLE IF NOT EXISTS `student` (
`SID` int(100) NOT NULL AUTO_INCREMENT,
`Name` varchar(100) NOT NULL,
`Address` varchar(500) NOT NULL,
`Email` varchar(100) NOT NULL,
`Mobile` varchar(25) NOT NULL,
PRIMARY KEY (`SID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=31 ;
Visual Studio 2012のインスタンスを開き、新しいASP.NETWebアプリケーションを作成します。次の図に示すように、プロジェクトに「MYSQLCRUDApplication」という名前を付け
ます。コードビハインドファイル(Student.aspx.cs)に、次のようにコードを記述します
Student.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="Student.aspx.cs" Inherits="MYSQLCRUDApplication.Student" %>
<asp:Content ID="Content1" ContentPlaceHolderID="titleContent" runat="server">
Simple Insert Select Update and Delete in ASP.NET using MySQL Database
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<table>
<tr>
<td class="td">Name:</td>
<td>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
<td>
<asp:Label ID="lblSID" runat="server" Visible="false"></asp:Label> </td>
</tr>
<tr>
<td class="td">Address:</td>
<td>
<asp:TextBox ID="txtAddress" runat="server"></asp:TextBox></td>
<td> </td>
</tr>
<tr>
<td class="td">Mobile:</td>
<td>
<asp:TextBox ID="txtMobile" runat="server"></asp:TextBox></td>
<td> </td>
</tr>
<tr>
<td class="td">Email ID:</td>
<td>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>
<td> </td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
<asp:Button ID="btnUpdate" runat="server" Text="Update" Visible="false"
OnClick="btnUpdate_Click" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click" /></td>
<td></td>
</tr>
</table>
<div style="padding: 10px; margin: 0px; width: 100%;">
<p>
Total Student:<asp:Label ID="lbltotalcount" runat="server" Font-Bold="true"></asp:Label>
</p>
<asp:GridView ID="GridViewStudent" runat="server" DataKeyNames="SID"
OnSelectedIndexChanged="GridViewStudent_SelectedIndexChanged"
OnRowDeleting="GridViewStudent_RowDeleting">
<Columns>
<asp:CommandField HeaderText="Update" ShowSelectButton="True" />
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />
</Columns>
</asp:GridView>
</div>
</asp:Content>
Web.configファイルで、次のように接続文字列を作成します。
Web.config
<connectionStrings>
<add name="ConnectionString"
connectionString="Server=localhost;userid=root;password=;Database=Testdb"
providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
ここで、コードビハインドファイル「Student.aspx.cs」で次のコードを使用します。
Student.aspx.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
namespace MYSQLCRUDApplication
{
public partial class Student : System.Web.UI.Page
{
#region MySqlConnection Connection and Page Lode
MySqlConnection conn = new
MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
Try
{
if (!Page.IsPostBack)
{
BindGridView();
}
}
catch (Exception ex)
{
ShowMessage(ex.Message);
}
}
#endregion
#region show message
/// <summary>
/// This function is used for show message.
/// </summary>
/// <param name="msg"></param>
void ShowMessage(string msg)
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script
language='javascript'>alert('" + msg + "');</script>");
}
/// <summary>
/// This Function is used TextBox Empty.
/// </summary>
void clear()
{
txtName.Text = string.Empty; txtAddress.Text = string.Empty; txtMobile.Text = string.Empty;
txtEmail.Text = string.Empty;
txtName.Focus();
}
#endregion
#region bind data to GridViewStudent
private void BindGridView()
{
Try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
MySqlCommand cmd = new MySqlCommand("Select * from Student ORDER BY SID DESC;",
conn);
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
GridViewStudent.DataSource = ds;
GridViewStudent.DataBind();
lbltotalcount.Text = GridViewStudent.Rows.Count.ToString();
}
catch (MySqlException ex)
{
ShowMessage(ex.Message);
}
Finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}
#endregion
#region Insert Data
/// <summary>
/// this code used to Student Data insert in MYSQL Database
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnSubmit_Click(object sender, EventArgs e)
{
Try
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("Insert into student (Name,Address,Mobile,Email )
values (@Name,@Address,@Mobile,@Email)", conn);
cmd.Parameters.AddWithValue("@Name",txtName.Text);
cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
cmd.Parameters.AddWithValue("@Mobile",txtMobile.Text);
cmd.Parameters.AddWithValue("@Email",txtEmail.Text);
cmd.ExecuteNonQuery();
cmd.Dispose();
ShowMessage("Registered successfully......!");
clear();
BindGridView();
}
catch (MySqlException ex)
{
ShowMessage(ex.Message);
}
Finally
{
conn.Close();
}
}
#endregion
#region SelectedIndexChanged
/// <summary>
/// this code used to GridViewRow SelectedIndexChanged value show textbox
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridViewStudent_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridViewStudent.SelectedRow;
lblSID.Text = row.Cells[2].Text;
txtName.Text = row.Cells[3].Text;
txtAddress.Text = row.Cells[4].Text;
txtEmail.Text = row.Cells[5].Text;
txtMobile.Text = row.Cells[6].Text;
btnSubmit.Visible = false;
btnUpdate.Visible = true;
}
#endregion
#region Delete Student Data
/// <summary>
/// This code used to GridViewStudent_RowDeleting Student Data Delete
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridViewStudent_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Try
{
conn.Open();
int SID = Convert.ToInt32(GridViewStudent.DataKeys[e.RowIndex].Value);
MySqlCommand cmd = new MySqlCommand("Delete From student where SID='" + SID + "'",
conn);
cmd.ExecuteNonQuery();
cmd.Dispose();
ShowMessage("Student Data Delete Successfully......!");
GridViewStudent.EditIndex = -1;
BindGridView();
}
catch (MySqlException ex)
{
ShowMessage(ex.Message);
}
Finally
{
conn.Close();
}
}
#endregion
#region student data update
/// <summary>
/// This code used to student data update
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnUpdate_Click(object sender, EventArgs e)
{
Try
{
conn.Open();
string SID = lblSID.Text;
MySqlCommand cmd = new MySqlCommand("update student Set
Name=@Name,Address=@Address,Mobile=@Mobile,Email=@Email where SID=@SID", conn);
cmd.Parameters.AddWithValue("@Name", txtName.Text);
cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
cmd.Parameters.AddWithValue("@Mobile", txtMobile.Text);
cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
cmd.Parameters.AddWithValue("SID",SID);
cmd.ExecuteNonQuery();
cmd.Dispose();
ShowMessage("Student Data update Successfully......!");
GridViewStudent.EditIndex = -1;
BindGridView(); btnUpdate.Visible = false;
}
catch (MySqlException ex)
{
ShowMessage(ex.Message);
}
Finally
{
conn.Close();
}
}
#endregion
#region textbox clear
protected void btnCancel_Click(object sender, EventArgs e)
{
clear();
}
#endregion
}
}
ページを実行すると、次のようになります。
次に、学生データの挿入とグリッドビューのデータの表示を入力します。メッセージボックス「正常に登録されました」。
次に、Studentを選択し、データTextBoxを表示して、メッセージボックス「StudentDataupdatesuccessfully」に表示されているデータを更新します。
ここで、メッセージボックス「StudentDataDeleteSuccessfully」に表示されているStudentデータを削除します。
この記事がお役に立てば幸いです。他にご不明な点がございましたら、以下にコメントをお寄せください。
リンク: https://www.c-sharpcorner.com/
1633367280
この記事では、ASP.NET WebアプリケーションからMySQLデータベースにデータの選択、更新、および削除を挿入する方法について説明します。
それでは、次の手順に進みましょう。
次に、MySQLAdminページを開き、[Create A New Table]-> [View]-> [Table Structure for Table`student`]を選択します。
CREATE TABLE IF NOT EXISTS `student` (
`SID` int(100) NOT NULL AUTO_INCREMENT,
`Name` varchar(100) NOT NULL,
`Address` varchar(500) NOT NULL,
`Email` varchar(100) NOT NULL,
`Mobile` varchar(25) NOT NULL,
PRIMARY KEY (`SID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=31 ;
Visual Studio 2012のインスタンスを開き、新しいASP.NETWebアプリケーションを作成します。次の図に示すように、プロジェクトに「MYSQLCRUDApplication」という名前を付け
ます。コードビハインドファイル(Student.aspx.cs)に、次のようにコードを記述します
Student.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="Student.aspx.cs" Inherits="MYSQLCRUDApplication.Student" %>
<asp:Content ID="Content1" ContentPlaceHolderID="titleContent" runat="server">
Simple Insert Select Update and Delete in ASP.NET using MySQL Database
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<table>
<tr>
<td class="td">Name:</td>
<td>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
<td>
<asp:Label ID="lblSID" runat="server" Visible="false"></asp:Label> </td>
</tr>
<tr>
<td class="td">Address:</td>
<td>
<asp:TextBox ID="txtAddress" runat="server"></asp:TextBox></td>
<td> </td>
</tr>
<tr>
<td class="td">Mobile:</td>
<td>
<asp:TextBox ID="txtMobile" runat="server"></asp:TextBox></td>
<td> </td>
</tr>
<tr>
<td class="td">Email ID:</td>
<td>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>
<td> </td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
<asp:Button ID="btnUpdate" runat="server" Text="Update" Visible="false"
OnClick="btnUpdate_Click" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click" /></td>
<td></td>
</tr>
</table>
<div style="padding: 10px; margin: 0px; width: 100%;">
<p>
Total Student:<asp:Label ID="lbltotalcount" runat="server" Font-Bold="true"></asp:Label>
</p>
<asp:GridView ID="GridViewStudent" runat="server" DataKeyNames="SID"
OnSelectedIndexChanged="GridViewStudent_SelectedIndexChanged"
OnRowDeleting="GridViewStudent_RowDeleting">
<Columns>
<asp:CommandField HeaderText="Update" ShowSelectButton="True" />
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />
</Columns>
</asp:GridView>
</div>
</asp:Content>
Web.configファイルで、次のように接続文字列を作成します。
Web.config
<connectionStrings>
<add name="ConnectionString"
connectionString="Server=localhost;userid=root;password=;Database=Testdb"
providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
ここで、コードビハインドファイル「Student.aspx.cs」で次のコードを使用します。
Student.aspx.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
namespace MYSQLCRUDApplication
{
public partial class Student : System.Web.UI.Page
{
#region MySqlConnection Connection and Page Lode
MySqlConnection conn = new
MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
Try
{
if (!Page.IsPostBack)
{
BindGridView();
}
}
catch (Exception ex)
{
ShowMessage(ex.Message);
}
}
#endregion
#region show message
/// <summary>
/// This function is used for show message.
/// </summary>
/// <param name="msg"></param>
void ShowMessage(string msg)
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script
language='javascript'>alert('" + msg + "');</script>");
}
/// <summary>
/// This Function is used TextBox Empty.
/// </summary>
void clear()
{
txtName.Text = string.Empty; txtAddress.Text = string.Empty; txtMobile.Text = string.Empty;
txtEmail.Text = string.Empty;
txtName.Focus();
}
#endregion
#region bind data to GridViewStudent
private void BindGridView()
{
Try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
MySqlCommand cmd = new MySqlCommand("Select * from Student ORDER BY SID DESC;",
conn);
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
GridViewStudent.DataSource = ds;
GridViewStudent.DataBind();
lbltotalcount.Text = GridViewStudent.Rows.Count.ToString();
}
catch (MySqlException ex)
{
ShowMessage(ex.Message);
}
Finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}
#endregion
#region Insert Data
/// <summary>
/// this code used to Student Data insert in MYSQL Database
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnSubmit_Click(object sender, EventArgs e)
{
Try
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("Insert into student (Name,Address,Mobile,Email )
values (@Name,@Address,@Mobile,@Email)", conn);
cmd.Parameters.AddWithValue("@Name",txtName.Text);
cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
cmd.Parameters.AddWithValue("@Mobile",txtMobile.Text);
cmd.Parameters.AddWithValue("@Email",txtEmail.Text);
cmd.ExecuteNonQuery();
cmd.Dispose();
ShowMessage("Registered successfully......!");
clear();
BindGridView();
}
catch (MySqlException ex)
{
ShowMessage(ex.Message);
}
Finally
{
conn.Close();
}
}
#endregion
#region SelectedIndexChanged
/// <summary>
/// this code used to GridViewRow SelectedIndexChanged value show textbox
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridViewStudent_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridViewStudent.SelectedRow;
lblSID.Text = row.Cells[2].Text;
txtName.Text = row.Cells[3].Text;
txtAddress.Text = row.Cells[4].Text;
txtEmail.Text = row.Cells[5].Text;
txtMobile.Text = row.Cells[6].Text;
btnSubmit.Visible = false;
btnUpdate.Visible = true;
}
#endregion
#region Delete Student Data
/// <summary>
/// This code used to GridViewStudent_RowDeleting Student Data Delete
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridViewStudent_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Try
{
conn.Open();
int SID = Convert.ToInt32(GridViewStudent.DataKeys[e.RowIndex].Value);
MySqlCommand cmd = new MySqlCommand("Delete From student where SID='" + SID + "'",
conn);
cmd.ExecuteNonQuery();
cmd.Dispose();
ShowMessage("Student Data Delete Successfully......!");
GridViewStudent.EditIndex = -1;
BindGridView();
}
catch (MySqlException ex)
{
ShowMessage(ex.Message);
}
Finally
{
conn.Close();
}
}
#endregion
#region student data update
/// <summary>
/// This code used to student data update
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnUpdate_Click(object sender, EventArgs e)
{
Try
{
conn.Open();
string SID = lblSID.Text;
MySqlCommand cmd = new MySqlCommand("update student Set
Name=@Name,Address=@Address,Mobile=@Mobile,Email=@Email where SID=@SID", conn);
cmd.Parameters.AddWithValue("@Name", txtName.Text);
cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
cmd.Parameters.AddWithValue("@Mobile", txtMobile.Text);
cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
cmd.Parameters.AddWithValue("SID",SID);
cmd.ExecuteNonQuery();
cmd.Dispose();
ShowMessage("Student Data update Successfully......!");
GridViewStudent.EditIndex = -1;
BindGridView(); btnUpdate.Visible = false;
}
catch (MySqlException ex)
{
ShowMessage(ex.Message);
}
Finally
{
conn.Close();
}
}
#endregion
#region textbox clear
protected void btnCancel_Click(object sender, EventArgs e)
{
clear();
}
#endregion
}
}
ページを実行すると、次のようになります。
次に、学生データの挿入とグリッドビューのデータの表示を入力します。メッセージボックス「正常に登録されました」。
次に、Studentを選択し、データTextBoxを表示して、メッセージボックス「StudentDataupdatesuccessfully」に表示されているデータを更新します。
ここで、メッセージボックス「StudentDataDeleteSuccessfully」に表示されているStudentデータを削除します。
この記事がお役に立てば幸いです。他にご不明な点がございましたら、以下にコメントをお寄せください。