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

  • 相关阅读:
    老王学jsp之javabean与表单
    老王学jsp之http500错误
    老王学jsp之session
    转 Fiddler抓取HTTPS
    PHP 大型网站优化 大数据大并发大流量
    大流量、高并发的网站的底层系统架构
    大流量、高并发Web系统搭建(单机到分布式集群)
    Failed to start Load Kernel Modules
    ubuntu 16.04 我的任务栏呢 怎么只剩下桌面了
    跳坑日志之腾讯服务器不见了
  • 原文地址:https://www.cnblogs.com/zhaoyids/p/14867326.html
Copyright © 2011-2022 走看看