asp.net webform使用MySQL資料庫
前臺:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="MySQL_Demo.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>
<style type="text/css">
table {
border:2px double red;
}
th {
border:2px double yellow;
width:100px;
color:blue;
}
td {
border:1px double yellow;
width:100px;
color:blue;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<%System.Data.DataTable tb = (System.Data.DataTable)Session["gtb"];%>
<table style="width: 100%;">
<tr>
<th>編號</th>
<th>城市</th>
<th>城市程式碼</th>
<th>描述</th>
<th>人口</th>
</tr>
<%foreach (System.Data.DataRow item in tb.Rows)
{%>
<tr>
<td><%:item[0] %></td>
<td><%:item[1] %></td>
<td><%:item[2] %></td>
<td><%:item[3] %></td>
<td><%:item[4] %></td>
</tr>
<%} %>
</table>
</div>
</form>
</body>
</html>
後臺:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
//引入MySQL的驅動
using MySql;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace MySQL_Demo
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strcon = ConfigurationManager.AppSettings["mysqlcon"].ToString();
string sql = "select * from city";
using (MySqlConnection con = new MySqlConnection(strcon))
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = sql;
cmd.Connection = con;
MySqlDataAdapter dr = new MySqlDataAdapter(cmd);
DataTable tb = new DataTable();
dr.Fill(tb);
Session["gtb"] = tb;//設定session,傳值到前臺
}
}
}
}
轉載於:https://blog.51cto.com/1433189426/1570852