基于vs2017的MySQL数据库连接

mysql数据库链接分为以下几步:
1、创建项目文件(asp.net web应用程序)
2、为项目添加mysql的驱动文件mysql.data.dll。(右键-添加-引用-浏览,在你本机mysql安装的目录中查找)
MySql.Data.dll提供以下8个类:
MySqlConnection: 连接MySQL服务器数据库。
MySqlCommand:执行一条sql语句。
MySqlDataReader: 包含sql语句执行的结果,并提供一个方法从结果中阅读一行。
MySqlTransaction: 代表一个SQL事务在一个MySQL数据库。
MySqlException: MySQL报错时返回的Exception。
MySqlCommandBuilder: Automatically generates single-table commands used to reconcile changes made to a DataSet with the associated MySQL database.
MySqlDataAdapter: Represents a set of data commands and a database connection that are used to fill a data set and update a MySQL database.
MySqlHelper: Helper class that makes it easier to work with the provider.
3、在项目根目录新建两个类,一个类是封装连接sql的语句,一个类是与数据库取得连接及查询数据库相关代码(增删改后期再更新)。

public static class DataConfig
{
public static string MYSQL_ConnectionString
{get
{
return "Server=Localhost;Database=userdata;Uid=root;pwd=888888;";
}
}
}

对于第二个类要注意添加引用;
using System.Data
using MySql.Data.MySqlClient;

public class clsDataOperate
{
public DataTable GetDatatableBySql(string sql)
{
MySqlConnection conn = new MySqlConnection();//数据库连接
conn.ConnectionString = DataConfig.MYSQL_ConnectionString; //链接方式琐死
 conn.Open();
 MySqlCommand mcom = new MySqlCommand();//执行数据库查询代码
 mcom.CommandText=sql;
 mcom.Connection=conn;
 MySqlDataAdapter mda = new MySqlDataAdapter(mcom);//更新数据库
 DataTable dt = new DataTable();
try
{
mda.Fill(dt);
conn.Close();
 return dt;
  }
catch (Exception ex)
  {
 return null;
  }
 finally
{
  conn.Close();
 }
}

4、webForm1.aspx代码:(这里继续数据控件绑定,用GridView控件)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<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="Button1" runat="server" Text="查询" OnClick="Button1_Click" />
            <asp:GridView ID="GridView1" runat="server"></asp:GridView>
        </div>
    </form>
</body>
</html>

5、业务处理层(这里是button对应的触发事件)
添加引用类using System.Data;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
    
        protected DataTable search = new DataTable();
        protected void Button1_Click(object sender, EventArgs e)
        {
            string sql = "select * from user";
            clsDataOperate cl = new clsDataOperate();
            search = cl.GetDataTableBySql(sql);
            GridView1.DataSource = search;//将查询结果反馈给gridview
            GridView1.DataBind();//数据绑定显示
            }}}
上一篇:Navicat Premium 15和VS2017的联动


下一篇:关闭VS2017中,启用浏览器中的JavaScript调试功能