C#连接数据库--VS中使用MYSQL connect Net 连接本地MYSQL

来源:互联网 发布:精美图案的3b编程 编辑:程序博客网 时间:2024/05/22 16:56

【步骤描述】

1、建立VC工程,把MYSQL装好,数据准备好

2、安装好MYSQL  connect Net 

3、在工程中引用MYSQL数据库对象

4、在代码中写连接和查询的语句




【在工程中引用MYSQL数据库对象】




【在代码中写连接和查询的语句】

[csharp] view plaincopy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. using MySql.Data.MySqlClient;       //使用连接和操作MySQL的方法,必须应用MySql.Data.MySqlClient  
  8.   
  9. namespace FirstMVC2Prj.Controllers  
  10. {  
  11.     [HandleError]  
  12.     public class HomeController : Controller  
  13.     {  
  14.         public ActionResult Index()  
  15.         {  
  16.   
  17.             String myInfo = "欢迎使用 ASP.NET MVC! ";  
  18.   
  19.             ///////////////////获取MYSQ看数据返回值////////////////////////////  
  20.             MySqlConnection myconn = null;  
  21.             MySqlCommand  mycom = null;  
  22.             MySqlDataReader myrec = null;  
  23.   
  24.             //连接字符串拼装  
  25.             myconn = new MySqlConnection("Host = localhost;Database = test;Username = root;Password = fulei");  
  26.   
  27.             //连接  
  28.             myconn.Open();  
  29.   
  30.             if(myconn.State.ToString()=="Open")  
  31.             {  
  32.                 myInfo = myInfo + "<br> 连接MYSQL成功";  
  33.             }  
  34.               
  35.             //查询命令赋值,可以写多条语句,多条语句之间用;号隔开  
  36.             mycom = new MySqlCommand("select * from persioninfo",myconn);  
  37.   
  38.             myrec = mycom.ExecuteReader();  
  39.   
  40.             //一次次读,读不到就结束  
  41.             while (myrec.Read())  
  42.             {  
  43.                 myInfo = myInfo + myrec["name"] + " " + myrec["sex"];  
  44.             }  
  45.   
  46.             //////关闭相关对象  
  47.             myrec.Close();  
  48.             myconn.Close();  
  49.   
  50.             /////////////////////获取MYSQ看数据返回值////////////////////////////  
  51.   
  52.              ViewData["Message"] = myInfo;  
  53.   
  54.             return View();  
  55.         }  
  56.   
  57.         public ActionResult About()  
  58.         {  
  59.             return View();  
  60.         }  
  61.     }  

  1. }  
0 0
原创粉丝点击