0%

C#安装 MySQL 驱动以及实现简单的 MySQL 操作

by 草梅友仁

一、驱动下载

首先前往 MySql 官网下载驱动。下载地址:https://dev.mysql.com/downloads/connector/net/

img

注意驱动版本即可。注意:要下载.zip 版本,解压后会看到几个 dll,那个就是需要的驱动

img

最新的 8.0.16 版本驱动要求.net 版本在 4.5 以上,如果需要 4.0 版本的则需要 6.8.8 版本,选择 4.0 版本驱动即可

image

img

由于本人安装的 Visual Studio 2010 最高只支持.net4.0,因此只能使用旧版驱动。不管哪个版本,MySQL 的核心驱动都是 MySql.Data.dll,使用的时候只需要引入这个即可

image

二、驱动引入

  1. 新建一个项目,名称随意。

img

  1. 找到项目位置,在项目根目录下新建 lib 文件夹

image

  1. 将 MySql.Data.dll 复制到该目录下

image

  1. 回到 Visual Studio 2010 中,右键添加添加引用

    image

  2. 选择浏览,找到 MySql.Data.dll,选中并点击确定

img

三、连接数据库

  1. 新建一个 Database.cs 类,并引用 MySql.Data.MySqlClient 类。注意类名前添加 public,否则无法在其他类中调用这个类

image

  1. 写一个初始化方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Database
{
static MySqlConnection conn;//MySql连接
const String server = "localhost";//服务器地址
const String uid = "test";//用户名
const String pw = "123456";//密码
const String db = "test";//库名
/// <summary>
/// 初始化程序,连接数据库
/// </summary>
public static Boolean Init()
{
try
{
if (conn == null)
{
conn = new MySqlConnection("server=" + server + ";user id=" + uid + ";password=" + pw + ";database=" + db);
conn.Open();
Console.WriteLine("数据库连接成功");
}
return true;
}
catch (Exception e)//异常处理
{
Console.WriteLine("Exception caught: {0}", e);
return false;
}
}
}

​ 3. 在主程序中调用该方法,观察控制台是否有输出,如果显示“数据库连接成功”则表明数据库连接已成功,操作正确。

image

img

四、编写数据库操作辅助类

对数据库的操作有很多重复的内容,因此这些可以像初始化方法这样提取出来。

  1. 查询操作

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    /// <summary>
    /// 查询操作,成功返回MySqlDataReader,具体的数据可以从该对象中获取;失败返回null
    /// </summary>
    public static MySqlDataReader Select(String sql)
    {
    try
    {
    Init();
    MySqlCommand command = new MySqlCommand(sql, conn);
    MySqlDataReader data = command.ExecuteReader();//这里返回从数据库获取的数据
    return data;
    }
    catch (Exception e)//注意了,对数据库的操作尤为要注意异常处理,因此直接写在这里即可
    {
    Console.WriteLine("Exception caught: {0}", e);
    return null;
    }
    }
  2. 增删改操作

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    /// <summary>
    /// 执行一条sql指令,成功返回true,失败返回fasle
    /// 事实上
    /// </summary>
    public static Boolean DbOp(String sql)
    {
    try
    {
    Init();
    MySqlCommand command = new MySqlCommand(sql, conn);
    int result = command.ExecuteNonQuery();//这里返回的是受影响的数据条数,如果不为零则表明操作成功
    return result != 0;
    }
    catch (Exception e)
    {
    Console.WriteLine("Exception caught: {0}", e);
    return false;
    }
    }
  3. 实现字符串的转义

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    /// <summary>
    /// 转义字符串 例如 abc 转为 'abc'
    /// </summary>
    public static String Escape(Object str)
    {
    if (str.GetType() == "".GetType())
    {//是字符串的进行防注入
    return "'" + MySqlHelper.EscapeString(str.ToString()) + "'";//注意,MySQL中表示字符串时一定需要单引号或反引号
    }
    return str.ToString();
    }

五、实现简单的增删查改功能

  1. 数据表名称:user

    字段:id,类型 int;name,类型 text;pw,类型 text

    img

如果要用 sql 语句创建,可参考如下,也可以用可视化工具创建

1
2
3
4
5
CREATE TABLE IF NOT EXISTS `user`(
`id` INT AUTO_INCREMENT PRIMARY KEY,
`name` TEXT NOT NULL,
`pw` TEXT NOT NULL
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
  1. 在项目中新建一个 User.cs 类,内容如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;

namespace MySqlTest
{
class User
{
public int id;//编号
public String name;//用户名
public String pw;//密码
public User()
{
}
public User(MySqlDataReader data)
{
this.id = data.GetInt16("id");
this.name = data.GetString("name");
this.pw = data.GetString("pw");
}
public User(String name, String pw)//注册时需要创建无id的新用户
{
this.name = name;
this.pw = pw;
}
public User(int id, String name, String pw)
{
this.id = id;
this.name = name;
this.pw = pw;
}
}
}

  1. 实现 user 的查询
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 /// <summary>
/// 根据id查找指定用户
/// </summary>
public static User SelectUser(int id)
{
string sql = "SELECT * from user WHERE id = " + id;
MySqlDataReader data = Select(sql);//如果出现异常会返回null,需要注意!!
if (data != null && data.Read())
{
User user = new User(data);//由于上面已经在User的的构造函数中写了相关方法,所以这里直接调用即可
data.Close();
return user;
}
else
{
if (data != null) //如果不为空则需要关闭!
{
data.Close();
}
return null;
}
}

3.实现 user 的增加

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 /// <summary>
/// 创建新用户
/// </summary>
public static User AddUser(User user)
{
String sql = "INSERT into user(id,name,pw) values(0," + Escape(user.name) + "," + Escape(user.pw) + ")";
if (DbOp(sql))
{
return SelectUser(user.name);
}
else
{
return null;
}
}

4.实现 user 的更新

1
2
3
4
5
6
7
8
/// <summary>
/// 修改用户
/// </summary>
public static Boolean UpdateUser(User user)
{
String sql = "UPDATE user SET name = " + Escape(user.name) + ",pw = " + Escape(user.pw) + " WHERE id = " + user.id;
return DbOp(sql);
}

5.实现 user 的删除

1
2
3
4
5
6
7
8
/// <summary>
/// 删除用户
/// </summary>
public static Boolean DeleteUser(int id)
{
String sql = "DELETE from user WHERE id = " + id;
return DbOp(sql);
}

本文作者:草梅友仁
本文地址: https://blog.cmyr.ltd/archives/9925ae75.html
版权声明:转载请注明出处!

三分钟搭建一个 vue-webpack 项目

by 草梅友仁

项目地址https://github.com/CaoMeiYouRen/simple-vue-webpack

上面的打不开可以访问这个地址https://gitee.com/caomeiyouren/simple-vue-webpack

使用

新建一个目录,然后切换到该目录

运行以下命令即可,前提是已经安装了 git

1
2
3
4
git clone https://github.com/CaoMeiYouRen/simple-vue-webpack.git
# github有点卡,如果上不去的话也可以换成下面这个链接
git clone https://gitee.com/caomeiyouren/simple-vue-webpack.git
# 注意以上命令只要运行一个即可

然后继续运行

1
2
3
4
5
6
npm i #下载依赖
npm run dev #开发模式,可通过http://127.0.0.1:3000 来访问
npm run build #生产模式,生成的文件在dist目录下
npm run server #启用http服务器,可通过http://127.0.0.1:80 来访问
npm run lint:fix #使用eslint修正风格
npm run uninstall #移除所有node_modules

运行效果

image

最后

由于本项目还是有些复杂的,因此建议直接看项目的 readme.md 文件,里面有详细解释

本文作者:草梅友仁
本文地址: https://blog.cmyr.ltd/archives/377812f1.html
版权声明:转载请注明出处!

npm 的使用

by 草梅友仁

参考链接https://www.runoob.com/nodejs/nodejs-npm.html

安装

由于新版的 nodejs 已经集成了 npm,所以之前 npm 也一并安装好了。同样可以通过输入 “npm -v” 来测试是否成功安装。命令如下,出现版本提示表示安装成功:

1
npm -v

image

如果你安装的是旧版本的 npm,可以很容易得通过 npm 命令来升级,命令如下:

1
2
3
4
#Linux
sudo npm install npm -g
#Windows
npm install npm -g

使用 npm 命令安装模块

npm 安装 Node.js 模块语法格式如下:

1
npm install <Module Name>

全局安装与本地安装

1
2
npm install express      # 本地安装
npm install express -g # 全局安装

卸载模块

我们可以使用以下命令来卸载 Node.js 模块。

1
npm uninstall express

更新模块

我们可以使用以下命令更新模块:

1
npm update express

搜索模块

使用以下来搜索模块:

1
npm search express

使用淘宝 NPM 镜像

你可以使用淘宝定制的 cnpm (gzip 压缩支持) 命令行工具代替默认的 npm:

1
npm install -g cnpm --registry=https://registry.npm.taobao.org

这样就可以使用 cnpm 命令来安装模块了:

1
cnpm install [name]

更多信息可以查阅:http://npm.taobao.org/

本文作者:草梅友仁
本文地址: https://blog.cmyr.ltd/archives/bddd47ac.html
版权声明:转载请注明出处!

Visual Studio Code 插件推荐

by 草梅友仁

参考链接

前言

Visual Studio Code 是一个非常适合用来写前端的编辑器,虽然本体功能简单,但是有着丰富而强大的插件支持,这使得 Visual Studio Code 可以深度自定义,实现你的需求。

插件推荐

那么,下面我就根据自己的使用体验来推荐一些插件。

  • Auto Close Tag 自动补全 HTML / XML 标签
  • Auto rename tag 自动重命名配对的 HTML / XML 标签
  • Auto Complete Tag 前两个插件的整合包
  • Auto Import 自动导入依赖包
  • Better Comments 高亮注释
  • change-case 修改代码命名风格
  • Chinese (Simplified) Language Pack for Visual Studio Code 中文简体汉化插件,习惯英语界面的也可以不装,英语苦手当然是必备的
  • Color Highlight 会将颜色代码转换为对应的颜色显示出来,这段代码什么颜色一目了然
  • Document This 给代码添加注释
  • DotENV .env 文件支持和格式化
  • EditorConfig for VS Code 使 vscode 支持 .editorconfig 配置
  • ESLint 代码检查工具,用于代码风格的检查。团队合作必备
  • file-peek 可以方便的补全文件路径
  • Git Graph 可视化 git 分支和提交记录
  • HTML Snippets HTML 代码片段
  • Image Preview 在编辑器上显示图片缩略图
  • IntelliSense for CSS class names in HTML 在 html 文件中提示 css 名称
  • JavaScript (ES6) code snippets es6 代码块
  • JavaScript and TypeScript Nightly 启用最新的 Typescript 语法
  • Markdown All in One 编写 md 文件
  • Markdown Preview Enhanced 可以把 vscode 当初 md 编辑器来使用,附带预览功能
  • npm Intellisense 自动提示 npm 包路径
  • Path Intellisense 自动提示 文件 路径
  • Polacode 生成美化代码的图片
  • open-in-browser 给 vscode 加一个右键在默认浏览器打开的快捷键
  • One Dark Pro 暗色主题。安装了 One Dark Pro 插件后,可以一键将 VSCode 编辑器的颜色调整成暗色系,编码起来更加舒适。
  • Simple React Snippets React 代码片段
  • stylelint css、scss、less 格式化
  • Todo Tree 统一查看项目下标记为 TODO 的注释
  • Vetur 前端神器,涵盖语法提示到格式化所有功能。也是 vue 框架推荐的插件。
  • Volar 对 Vue3 + Typescript 进行了专门的优化,注意和 Vetur 功能冲突,装其中一个就好了。如果使用 Typescript 开发,则该插件能提供更多的 Typescript 信息,所以更推荐安装该插件。如果使用 JavaScript 开发,那么效果差不多,都可以
  • vscode-icons 可以让 vscode 中的文件管理的树目录显示图标,显示图标后会使得文件、文件夹更加明确功能
  • WakaTime 记录写代码的时间
  • YAML yml/yaml 格式文件提示

以上插件在 Visual Studio Code 直接搜索即可~

娱乐向插件推荐

以下插件偏向娱乐性,请在开发中慎用~

  • 小霸王 小霸王是一款基于 vscode 的 nes 游戏插件,能让你在紧张的开发之余在 vscode 里发松身心。通过劳逸结合,提升开发效率。
    • 请务必在闲暇时间使用本插件,若是上班摸鱼被发现,后果自负
  • cloudmusic 网易云音乐插件。在 vscode 中听音乐,实现了播放器的大部分功能。
    • 本插件也请务必在闲暇时间使用~
    • 注意,如果无法使用本插件例如插件初始化失败,请安装 Visual C++ 2017 后重试。
  • swimming VSCode 模拟写代码,划水,摸鱼神器
  • Rainbow Fart VSCode Rainbow Fart 是一个在你编程时持续夸你写的牛逼的扩展,可以根据代码关键字播放贴近代码意义的真人语音。

本文作者:草梅友仁
本文地址: https://blog.cmyr.ltd/archives/44a0df8f.html
版权声明:转载请注明出处!

如何三分钟将网站转换为 APP?

by 草梅友仁

前言

现在用前端技术来写一个 app 实在是太方便了,尤其是有像 HBuilder(现已更名为 HBuilderX,功能一样)能将原生 H5 打包成原生 APP 的软件,那就更加方便了。

下面我们就来看看,如何在三分钟之内将你的网站转换为 APP。

【本案例以草梅友仁自己的个人网站https://www.caomeiyouren.cn/为例】

0.首先

首先,你肯定得先做好一个网站,也已经适配好了手机。但毕竟只是一个网站,还要通过手机浏览器来访问,有点不方便,如果能打包成 app 岂不美哉?【如图,已经做好了手机适配】

Screenshot_2019-05-15-21-28-49-39

1.使用 HBuilder 新建移动 App 工程

先用 HBuilder 建一个空的移动 App 工程

image

2.在 index.html 页面添加如下代码

1
2
3
4
<script type="text/javascript">
window.location.href = "https://www.caomeiyouren.cn/#/index";
//这段代码的意思是跳转到指定网页
</script>

3.配置 App 信息

image

4.发行打包

image image

5.下载 app 到手机试用

Screenshot_2019-05-15-22-10-01-74

效果可以说是非常完美了!

6.优化用户体验

但是这个时候又会遇到新的问题了。

  • 用户一旦按了手机的物理退出键,会触发 app 的默认退出事件,也就是说这个 app 就直接退出了

    解决方案如下,在你的网站首页添加这样一段代码。请注意,是你的网站首页!

    本段示例仅适用于单页面应用。多页面应用需要每个页面都有这么一段。

    同时为了避免在首页还会返回原来页面的 bug,建议通过路由来判断是否为首页

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    <script>
    /* 解决App端物理返回键的问题 */
    document.addEventListener('plusready', function () {
    var webview = plus.webview.currentWebview();
    plus.key.addEventListener('backbutton', function () {
    webview.canBack(function (e) {
    //通过哈希路由来判断是否为首页,是首页则按返回键退出。避免退出后还会返回原来页面的BUG
    if (e.canBack && location.hash !== "#/index") {
    webview.back();//返回上一个页面
    } else {
    //首页返回键处理
    //处理逻辑:1秒内,连续两次按返回键,则退出应用;
    var first = null;
    plus.key.addEventListener('backbutton', function () {
    //首次按键,提示‘再按一次退出应用’
    if (!first) {
    first = new Date().getTime();
    plus.nativeUI.toast('再按一次退出应用');
    setTimeout(function () {
    first = null;
    }, 1000);
    } else {
    if (new Date().getTime() - first < 1500) {
    plus.runtime.quit();
    }
    }
    }, false);
    }
    })
    });
    });
    </script>

本文作者:草梅友仁
本文地址: https://blog.cmyr.ltd/archives/a7652497.html
版权声明:转载请注明出处!