search
HomeDatabaseMysql Tutorial关于C# 连接Mysql

关于C# 连接Mysql

Jun 07, 2016 pm 03:40 PM
mysqlaboutreasonconnect

缘起 由于一些特别的原因,我再次短暂的回到 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); 
        }
    }
}

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();
            }
        }
    }
}

备注: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
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
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 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.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles

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 Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software