0、写在前面
上一篇文章我们已经成功写出了返回固定数据的接口,现在我们就来连接数据库,从数据库里获取信息并在接口里返回。这里给出的项目代码是在正式项目里使用的。
1、安装MySQL数据库
之前看过 一、vue入门基础开发—手把手教你用vue开发 这篇文章下载过 phpstudy 的小伙伴请打开路径 phpstudy_pro\Extensions ,里面已经有了一个mysql数据库,默认账户密码都是 root 。没有的小伙伴请参考文章 菜鸟教程-win10安装mysql详细教程,写的非常详细。
启用 / 停止 数据库
2、连接数据库
修改 Controllers/HomeController.cs,数据库信息在正式项目中放到 webconfig或者 配置文件中。
......
+ using MySql.Data.MySqlClient;
.....
+ public JsonResult MysqlDatabase()
+ {
+ String connetStr = "server=localhost;port=3306;user=root;password=root;";
+ String isConnection = "否";
+ MySqlConnection conn = new MySqlConnection(connetStr);
+ try
+ {
+ conn.Open();
+ isConnection = "是";
+ }
+ catch (MySqlException ex)
+ {
+ Console.WriteLine(ex.Message);
+ }
+ finally
+ {
+ conn.Close();
+ }
+ return Json(new { isConnection = isConnection}, JsonRequestBehavior.AllowGet);
+ }
修改 Views/Home/Test.cshtml
+ $.ajax({
- url: '/home/json1',
+ url: '/home/MysqlDatabase',
dataType: 'json',
success(data) {
console.log(data)
}
})
3、数据表操作
(1)安装 Navicat for MySQL
为了可视化管理mysql我们安装 Navicat for MySQL,完成后新建连接,并测试连接成功。
(2)新建数据库表
右击选择添加数据库
添加数据表link,并添加数据
(3)获取数据
新建Model/User.cs
using System;
namespace MyWebApp.com.Models
{
public class User
{
public int? ID { get; set; }
public String Name { get; set; }
public int? Age { get; set; }
}
}
修改 Controllers/HomeController.cs,在正式项目中这种数据处理一般是写在Model或者库类里面的。
......
+ using MyWebApp.com.Models;
......
public JsonResult MysqlDatabase()
{
- String connetStr = "server=localhost;port=3306;user=root;password=root;";
+ String connetStr = "server=localhost;port=3306;user=root;password=root;database=testnet;";
String isConnection = "否";
+ String sql = "select * from link;";
+ List UserLists = new List();
MySqlConnection conn = new MySqlConnection(connetStr);
try
{
conn.Open();
isConnection = "是";
+ MySqlCommand cmd = new MySqlCommand(sql, conn);
+ MySqlDataReader reader = cmd.ExecuteReader();
+ while (reader.Read())
+ {
+ User UserList = new User();
+ UserList.ID = Convert.ToInt32(reader["id"]);
+ UserList.Name = reader["name"].ToString();
+ UserList.Age = Convert.ToInt32(reader["age"]);
+ UserLists.Add(UserList);
+ }
+ reader.Close();
}
catch (MySqlException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
conn.Close();
}
- return Json(new { isConnection = isConnection }, JsonRequestBehavior.AllowGet);
+ return Json(new { isConnection = isConnection,list= UserLists }, JsonRequestBehavior.AllowGet);
保存运行一下,如下图,成功获取数据。
(4)ExecuteNonQuery()——删改查
4、正式项目的使用
新建库类,在解决方案上右击选择新建项目,这么可以把业务处理、类跟数据处理都独立开。
a、新建项目
b、新建库
c、写代码
d、添加引用
连接MySQL数据库到此结束。
感谢阅读,喜欢的话点个赞吧:)
更多内容请关注后续文章。。。