ASP.NET连接MySQL数据库

ASP.NET可以连接很多种数据库,本文以连接MySQL数据库,并以实现简单的增删改查功能做一个小小小Demo。

步骤

  1. 在MySQL数据库建库(名为yimi);建表(名为plan);插入若干数据。
    1
  2. 使用VS2017(这是我用的版本,其他版本应该也差别不大)新建ASP.NET Web应用程序。
    2
  3. 在所建号的网站项目右侧的“解决方案资源管理器”内的“引用”处,单击右键“添加引用”,然后“浏览”找到安装MySQL的地方中自带的“MySql.Data.dll”文件(比如我的文件默认安装在了C:\Program Files (x86)\MySQL\MySQL Connector Net 6.10.5\Assemblies\v4.5.2),点击添加。
    3
  4. 新建一个aspx页面(WebForm1.aspx),添3个按钮(ButtonAdd、ButtonDelete、ButtonUpdate)和一个标签(Label1)。
    4
    代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication3.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>

            <asp:Button ID="ButtonAdd" runat="server" OnClick="ButtonAdd_Click" Text="增" />
            <asp:Button ID="ButtonDelete" runat="server" OnClick="ButtonDelete_Click" Text="删" />

            <asp:Button ID="ButtonUpdate" runat="server" OnClick="ButtonUpdate_Click" Text="改" />

        </div>
        <p>
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        </p>
    </form>
</body>
</html>
  1. 修改配置文件Web.config,添加连接数据库的相关配置。
    5
    新添部分具体代码如下:
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-Sanlogic.MSTWebsite-20140219093639;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-Sanlogic.MSTWebsite-20140219093639.mdf" providerName="System.Data.SqlClient" />

    <add name="DBConnection"   connectionString="server=localhost;user id=root;password=wanxinyan;database=yimi; pooling=true;"
           providerName="MySql.Data.MySqlClient" />

  </connectionStrings>

其中服务器地址、数据库、用户id、密码根据自己实际情况来填写。
6. 修改所添加的页面的后台逻辑(WebForm1.aspx.cs文件),其中增、删、改按钮通过双击“设计”页面中的控件也可自动生成对应方法。

using MySql.Data.MySqlClient;
using System;
using System.Web.Configuration;

namespace WebApplication3
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            MySqlConnection conn = CreateConn();
            string sqlQuery = "SELECT * FROM plan";
            MySqlCommand comm = new MySqlCommand(sqlQuery, conn);
            conn.Open();
            MySqlDataReader dr = comm.ExecuteReader();
            if (dr.Read())
            {
                Label1.Text = (String)dr[1].ToString().Trim();
            }
            conn.Close();
        }
        public static MySqlConnection CreateConn()
        {
            string _conn = WebConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
            MySqlConnection conn = new MySqlConnection(_conn);
            return conn;
        }

        protected void ButtonDelete_Click(object sender, EventArgs e)
        {
            MySqlConnection conn = CreateConn();
            string sql = "delete from plan where id=1";
            MySqlCommand comm = new MySqlCommand(sql, conn);
            conn.Open();
            comm.ExecuteNonQuery();
            conn.Close();
        }

        protected void ButtonAdd_Click(object sender, EventArgs e)
        {
            MySqlConnection conn = CreateConn();
            string sql = "insert into plan(id,name) values(3,'新增数据')";
            MySqlCommand comm = new MySqlCommand(sql, conn);
            conn.Open();
            comm.ExecuteNonQuery();
            conn.Close();
        }

        protected void ButtonUpdate_Click(object sender, EventArgs e)
        {
            MySqlConnection conn = CreateConn();
            string sql = "update plan set name='小制作计划' where id=1";
            MySqlCommand comm = new MySqlCommand(sql, conn);
            conn.Open();
            comm.ExecuteNonQuery();
            conn.Close();
        }
    }
}

7.运行。
可以看到标签所显示的内容(“休闲计划”)是从数据库中查出的:
6
8. 依次点击增、删、改按钮,然后刷新数据库的表,可以看到表已经有了变化。
旧表:
1
新表:
7
至此,通过ASP.NET连接MySQL数据库并实现简单的增删改查功能均已实现。

  • 25
    点赞
  • 158
    收藏
    觉得还不错? 一键收藏
  • 12
    评论
可以使用以下代码实现asp.net连接MySQL数据库: ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using MySql.Data.MySqlClient; public class MySQLDBHelper { private static string connectionString = "server=localhost;user id=root;password=123456;database=test;Charset=utf8;"; public static DataTable ExecuteDataTable(string commandText, CommandType commandType, params MySqlParameter[] parameters) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { using (MySqlCommand command = new MySqlCommand(commandText, connection)) { command.CommandType = commandType; if (parameters != null) { command.Parameters.AddRange(parameters); } MySqlDataAdapter adapter = new MySqlDataAdapter(command); DataTable dataTable = new DataTable(); adapter.Fill(dataTable); return dataTable; } } } public static int ExecuteNonQuery(string commandText, CommandType commandType, params MySqlParameter[] parameters) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { using (MySqlCommand command = new MySqlCommand(commandText, connection)) { command.CommandType = commandType; if (parameters != null) { command.Parameters.AddRange(parameters); } connection.Open(); int result = command.ExecuteNonQuery(); return result; } } } } ``` 其中,MySQLDBHelper是一个帮助类,提供了两个静态方法,一个用于执行SELECT语句并返回DataTable,另一个用于执行INSERT/UPDATE/DELETE等操作并返回受影响的行数。需要将connectionString变量替换为自己的MySQL连接字符串。使用示例: ``` MySqlParameter[] parameters = new MySqlParameter[] { new MySqlParameter("@name", "张三"), new MySqlParameter("@age", 20) }; string sql = "INSERT INTO student (name, age) VALUES (@name, @age)"; int result = MySQLDBHelper.ExecuteNonQuery(sql, CommandType.Text, parameters); if (result > 0) { Response.Write("添加成功!"); } else { Response.Write("添加失败!"); } ```
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值