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

步骤

(1)在MySQL数据库建库;建表;插入若干数据。

 

          使用VS2012(这是我用的版本,其他版本应该也差别不大)新建ASP.NET Web应用程序。

 

(2)添加引用。

        在所建号的网站项目右侧的“解决方案资源管理器”内的“引用”处,单击右键“添加引用”,然后“浏览”找到安装MySQL的地方中自带的“MySql.Data.dll”文件(比如我的文件默认安装在了C:\\Program Files (x86)\\MySQL\\MySQL Connector Net 6.10.5\\Assemblies\\v4.5.2),点击添加。

\"\"

(3)web.config文件的配置

 <connectionStrings>

   <add name=\"DefaultConnection\" connectionString=\"Date Source=(LocalDb)\\v11.0;Initial Catalog=ASP\" />
  <add name=\"DBConnection\" connectionString=\"server=localhost;user     id=root;password=0000;Data =ASP;Charset=gb2312\" providerName=\"MySql.Data.MySqlClient\" />

 </connectionStrings>

(4)各种SQL语句

//必需的头文件
using MySql.Data.MySqlClient;
using System;
using System.Web.Configuration;
 
namespace WebApplication3
{
    public partial class WebForm1 : System.Web.UI.Page
    {
//通用链接
      public static MySqlConnection CreateConn()
        {
            string _conn = WebConfigurationManager.ConnectionStrings[\"DBConnection\"].ConnectionString;
            MySqlConnection conn = new MySqlConnection(_conn);
            return conn;
        }


//查询 
       protected void Page_Load(  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();
        }
  
 //删除
        protected void ButtonDelete_Click(  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(  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(  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();
        }
    }
}

 

收藏 打印