1. 程式人生 > 實用技巧 >.net連線MySQL資料庫

.net連線MySQL資料庫

1、通過Visual Stdio新建.net專案

(1)新建專案

(2)選擇專案配置

(3)專案結構

(4)新建一個Controller,名稱要取HomeController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        
// GET: Home public String Index() { return "Hello world"; } } }

測試:

2、建立ODBC資料來源

(1)下載ODBC資料來源

(2)配置ODBC資料來源

新增相關的資訊後點擊測試:

3、.net連線MySQL資料庫

方式一:

(1)新增引用

(2)新增一個Web窗體

(3)設計頁面

選擇工具:

(4)連線資料來源

雙擊SQL資料庫

(5)測試

(6)執行生成的頁面即可

(7)生成的程式碼如下

<%@ Page Language="
C#" AutoEventWireup="true" CodeBehind="students.aspx.cs" Inherits="WebApplication1.students" %> <!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:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="stu"> <Columns> <asp:BoundField DataField="studentno" HeaderText="studentno" InsertVisible="False" SortExpression="studentno" /> <asp:BoundField DataField="birthday" HeaderText="birthday" SortExpression="birthday" /> <asp:BoundField DataField="classno" HeaderText="classno" SortExpression="classno" /> <asp:BoundField DataField="phone" HeaderText="phone" SortExpression="phone" /> <asp:BoundField DataField="sex" HeaderText="sex" SortExpression="sex" /> <asp:BoundField DataField="sname" HeaderText="sname" SortExpression="sname" /> <asp:BoundField DataField="score" HeaderText="score" SortExpression="score" /> </Columns> </asp:GridView> <asp:SqlDataSource ID="stu" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>" SelectCommand="select *from student"> </asp:SqlDataSource> </div> </form> </body> </html>

方式二:

在配置檔案中書寫資料來源有關的配置

 <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=root; database=student; pooling=true;" providerName="MySql.Data.MySqlClient" /> </connectionStrings>

通過讀取配置檔案來獲取連線