zoukankan      html  css  js  c++  java
  • 11.17

    c#数据库操作类

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Configuration;
    using MySql.Data.MySqlClient;
    using System.Data;
    namespace WindowsFormsApp1
    {
    public class DBHelper
    {

    private static readonly String s = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
    public static int ExecuteNonQuery(string sql,int cmdType,params MySqlParameter[]paras )
    {
    int count = 0;
    using (MySqlConnection conn = new MySqlConnection(s))
    {
    MySqlCommand cmd = new MySqlCommand(sql, conn);
    if (cmdType == 2)
    cmd.CommandType = CommandType.StoredProcedure;
    if (paras != null && paras.Length > 0)
    {
    cmd.Parameters.AddRange(paras);
    }
    conn.Open();
    count = cmd.ExecuteNonQuery();


    }
    return count;
    }
    public static object ExecuteScalar(string sql, int cmdType, params MySqlParameter[] paras)
    {
    object o=null;
    using (MySqlConnection conn = new MySqlConnection(s))
    {
    MySqlCommand cmd = new MySqlCommand(sql, conn);
    if (cmdType == 2)
    cmd.CommandType = CommandType.StoredProcedure;
    if (paras != null && paras.Length > 0)
    {
    cmd.Parameters.AddRange(paras);
    }
    conn.Open();
    o = cmd.ExecuteScalar();


    }
    return o;
    }

    public static MySqlDataReader ExecuteReader(string sql, int cmdType, params MySqlParameter[] paras)
    {
    MySqlDataReader o = null;
    MySqlConnection conn = new MySqlConnection(s);

    MySqlCommand cmd = new MySqlCommand(sql, conn);

    if (cmdType == 2)
    cmd.CommandType = CommandType.StoredProcedure;
    if (paras != null && paras.Length > 0)
    {
    cmd.Parameters.AddRange(paras);
    }
    try
    {
    conn.Open();
    o = cmd.ExecuteReader(CommandBehavior.CloseConnection);

    }
    catch(MySqlException ex)
    {
    conn.Close();
    throw new Exception("执行查询异常", ex);
    }


    return o;
    }
    public static DataTable GetDataTable(String sql, params MySqlParameter[] paras)
    {
    DataTable o = new DataTable();
    using (MySqlConnection conn = new MySqlConnection(s))
    {
    MySqlCommand cmd = new MySqlCommand(sql, conn);

    if (paras != null && paras.Length > 0)
    {
    cmd.Parameters.AddRange(paras);
    }
    //conn.Open();
    MySqlDataAdapter da = new MySqlDataAdapter();
    da.SelectCommand = cmd;
    da.Fill(o);


    }
    return o;
    }
    }
    }

  • 相关阅读:
    第一个
    一点收获
    又是两个小时
    大学坑真多
    步入正轨
    linux find grep 查找命令
    ROS下使用ASUS Xtion Pro Live
    更改文件所有者和群组
    如何在Ubuntu 14.04中安装最新版Eclipse
    1.关于无rospy.spin()调用多次callback 2. subscrib后面语句和callback函数运行顺序
  • 原文地址:https://www.cnblogs.com/zhaoyids/p/14867326.html
Copyright © 2011-2022 走看看