1.添加mysql引用
- 方式一:下载 MySql.Data.dll文件 这里下载
然后将在当前web项目中将选择添加引用,将此文件添加进去 - 方式二:在NuGet包管理器中添加Mysql.Data包到当前项目(不需要自己添加引用)
2.在web.config 文件中添加数据库连接字符串
-
<connectionStrings> <add name=\"test1ConnectionString\"connectionString=\"server=ip;uid=userName;pwd=password;database=dbname\" providerName=\"MySql.Data.MySqlClient\" /> </connectionStrings>
3.创建web窗体连接数据库
-
demo1.aspx
-
<asp:GridView ID=\"GridView1\" runat=\"server\" Style=\"margin-right: 0px\"></asp:GridView> <asp:Button ID=\"Button1\" runat=\"server\" Text=\"Button\" OnClick=\"Button1_Click\" />
-
` demo1.aspx.cs
string connection = ConfigurationManager.ConnectionStrings[\"test1ConnectionString\"].ConnectionString;MySqlConnection conn = new MySqlConnection(connection);conn.Open();//MySql查询语句string sqlQuery = \"SELECT * FROM account\";//执行查询MySqlCommand cmd = new MySqlCommand(sqlQuery, conn);MySqlDataAdapter data = new MySqlDataAdapter();data.SelectCommand = cmd;//将查询结果注入到dataset Ds中DataSet Ds = new DataSet();data.Fill(Ds);//将查询结果绑定到GridView1上this.GridView1.DataSource = Ds;this.GridView1.DataBind();conn.Close();
`