Table of Contents
缘起
正文
1. C#连接Mysql
2. MySQLHelper辅助类
后记
参考文献
Home Database Mysql Tutorial 关于C# 连接Mysql

关于C# 连接Mysql

Jun 07, 2016 pm 03:40 PM
mysql about reason connect

缘起 由于一些特别的原因,我再次短暂的回到 Windows ,回到了 VisualStudio2010 和 C# 。习惯了 Ubuntu/Linux 的快速高效的开发环境,对 Windows 下的开发工具的庞大臃肿反应慢既愤慨又无奈。由于不想使用和 VisaulStudio2010 相同的臃肿的开发环境,就使用

缘起

由于一些特别的原因,我再次短暂的回到Windows,回到了Visual Studio 2010C#。习惯了Ubuntu/Linux的快速高效的开发环境,对Windows下的开发工具的庞大臃肿反应慢既愤慨又无奈。由于不想使用和Visaul Studio 2010相同的臃肿的开发环境,就使用C#+Mysql这个组合。以下是一些记录。

正文

连接数据库最重要是找到驱动程序,ODBC、JDBC是数据库连接的接口的标准,实现这些接口称为驱动程序。无论什么语言何种平台,都需要连接数据库都需要相应的驱动器。比如连接Mysql数据库,Java就需要Java的连接器,.NET就需要.NET的连接器,像Ruby这类的脚本程序也需要相应的数据库连接包。

关于在Windows下用C#开发应用程序,如果是ASP.NET+C#的话,没的选,只有Visual Studio;如果开发C#WinForm程序或控制台程序,IDE可以选择SharpDevelop或者MonoDevelopSharpDevelop的启动速度很快,几乎秒开,但SharpDevelop只适用WindowsMonoDevelop可以跨平台,可以在WindowsLinux下使用。

1. C#连接Mysql

关于C#连接数据库方法是使用Mysql官方的提供的connector-net的包,然后将其引用到项目中,这个方式可以适用与任何使用C#开发的程序,包括Visual StudioMonoDevelop创建的项目。具体的操作步骤如下:

1.下载connector

Mysqlconnector-net下载地址:http://dev.mysql.com/downloads/connector/net/

20145月份,最新的连接版本是:6.8.3,该包中含有的文件:

关于C# 连接Mysql

其中,Vx.0表示的是.NETFramework的版本号,根据项目使用的.NETFramework选择相应的目录下的Mysql.**.dll

2.在项目中引用 mysql-connector-net包中的MySql.Data.dll(注意引用和项目使用框架相同的版本dll

3.设置数据库连接字符串

字符串的样例如下:

Server=localhost;user id=root;password=localhost;Database=web;Port=3306;charset=utf8;

一般而言,这里需要修改的只有password和database,其他的都可以使用默认。

4.简单测试数据库连接的demo程序

using System;
using System.Collections.Generic;
using MySql.Data.MySqlClient;//引用Mysql.data.dll中的类
 
namespace testdb
{
    class Program
    {
        static void Main(string[] args)
        {
            string query = "select * from t_user";
            MySqlConnection myConnection = new MySqlConnection("server=localhost;user id=root;password=11;database=db_user");
            MySqlCommand myCommand = new MySqlCommand(query, myConnection);
            myConnection.Open();
            myCommand.ExecuteNonQuery();
            MySqlDataReader myDataReader = myCommand.ExecuteReader();
            string bookres = "";
            while (myDataReader.Read() == true)
            {
                bookres += myDataReader["id"];
                bookres += myDataReader["userName"];
                bookres += myDataReader["password"];
            }
            myDataReader.Close();
            myConnection.Close();
            Console.WriteLine(bookres); 
        }
    }
}
Copy after login

2. MySQLHelper辅助类

像上面的测试连接的样例中那样,每次都自己编写相应的连接之类的非常不方便,此时,可以考虑使用一个DBhelper这样的辅助类来减少重复代码。下面是一个简单的Dbheper辅助类:

public class MySQLHelper
{
    private static string connectionString = ConfigurationManager.ConnectionStrings["mysqlconn"].ConnectionString;
    /// <summary>
    /// 执行查询语句,返回DataSet
    /// </summary>
    /// <param name="SQLString">查询语句
    /// <returns>DataSet</returns>
    public static DataSet Query(string SQLString)
    {
        using (MySqlConnection connection = new MySqlConnection(connectionString))
        {
            DataSet ds = new DataSet();
            try
            {
                connection.Open();
                MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
                command.Fill(ds);
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                connection.Close();
            }
            return ds;
        }
    }
    /// <summary>
    /// 执行SQL语句,返回影响的记录数
    /// </summary>
    /// <param name="SQLString">SQL语句
    /// <returns>影响的记录数</returns>
    public static int ExecuteSql(string SQLString)
    {
        using (MySqlConnection connection = new MySqlConnection(connectionString))
        {
            using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
            {
                try
                {
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (System.Data.SqlClient.SqlException e)
                {
                    connection.Close();
                    throw e;
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }
    }
    /// <summary>
    /// 执行SQL语句,返回影响的记录数
    /// </summary>
    /// <param name="SQLString">SQL语句
    /// <returns>影响的记录数</returns>
    public static int ExecuteSql(string[] arrSql)
    {
        using (MySqlConnection connection = new MySqlConnection(connectionString))
        {
 
            try
            {
                connection.Open();
                MySqlCommand cmdEncoding = new MySqlCommand(SET_ENCODING, connection);
                cmdEncoding.ExecuteNonQuery();
                int rows = 0;
                foreach (string strN in arrSql)
                {
                    using (MySqlCommand cmd = new MySqlCommand(strN, connection))
                    {
                        rows += cmd.ExecuteNonQuery();
                    }
                }
                return rows;
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                connection.Close();
                throw e;
            }
            finally
            {
                connection.Close();
            }
        }
    }
}
Copy after login

备注:SQLserver代码改写成mysql很容易,由于二者格式几乎一样,而改写的部分也很少。

后记

再次回到Windows修改C#WinForm程序,让我反思了一些问题,比如Rails到底能做到什么,桌面程序和web程序优缺点这类的问题,也算不错。不过,再次明白windows确实不是一个好的开发环境。

回想起来,自己当初在选择技术时,选择的是C#,为此花费了一年的时间来学习C#。后来,跟老师搞研究,转战Java,最后,在拥抱ubuntu一年后,选择了RailsRuby作为谋生的工具。这次,再次回到短暂的windows上,让我想到当初花了很长的时间学习,也应该积累了很多的经验,可惜的是都没有记下来,然后,就全忘光了。

参考文献

1..net mysql-connector-net连接mysql

2.asp.net连接Mysql(connector/net 5.0)

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

Solve MySQL mode problem: The experience of using the TheliaMySQLModesChecker module Solve MySQL mode problem: The experience of using the TheliaMySQLModesChecker module Apr 18, 2025 am 08:42 AM

When developing an e-commerce website using Thelia, I encountered a tricky problem: MySQL mode is not set properly, causing some features to not function properly. After some exploration, I found a module called TheliaMySQLModesChecker, which is able to automatically fix the MySQL pattern required by Thelia, completely solving my troubles.

Explain the purpose of foreign keys in MySQL. Explain the purpose of foreign keys in MySQL. Apr 25, 2025 am 12:17 AM

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

Compare and contrast MySQL and MariaDB. Compare and contrast MySQL and MariaDB. Apr 26, 2025 am 12:08 AM

The main difference between MySQL and MariaDB is performance, functionality and license: 1. MySQL is developed by Oracle, and MariaDB is its fork. 2. MariaDB may perform better in high load environments. 3.MariaDB provides more storage engines and functions. 4.MySQL adopts a dual license, and MariaDB is completely open source. The existing infrastructure, performance requirements, functional requirements and license costs should be taken into account when choosing.

See all articles