C#链接MySQL数据库的实现步骤有哪些

如题所述

C#连接数据库有以下几个步骤:
1:使用配置的数据库连接串,创建数据库连接 Connection 对象
2:构建操作的sql语句
3:定义command对象
4:打开数据连接
5:执行命令
举一个例子,删除操作  

public class StudentService
    {
        //从配置文件中读取数据库连接字符串
        private readonly static string connString = ConfigurationManager.ConnectionStrings["accpConnectionString"].ToString();
        private readonly static string dboOwner = ConfigurationManager.ConnectionStrings["DataBaseOwner"].ToString();
        AdoNetModels.Student model = new Student();
   
        #region  åˆ é™¤æ•°æ®1
        public int DeleteStudent(int stuID)
        {
            int result = 0;
            // æ•°æ®åº“连接 Connection å¯¹è±¡
            SqlConnection connection = new SqlConnection(connString);
            // æž„建删除的sql语句
            string sql = string.Format("Delete From Student  Where stuID={0}", stuID);
            // å®šä¹‰command对象
            SqlCommand command = new SqlCommand(sql, connection);

            try
            {
                connection.Open();
                result = command.ExecuteNonQuery();  // æ‰§è¡Œå‘½ä»¤
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.Message);
            }
            finally
            {
                connection.Close();
            }
            return result;
        }
        #endregion
温馨提示:答案为网友推荐,仅供参考