C#winform应用程序连接sql server数据库代码

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/h273979586/article/details/77148935

一、用于查询语句,查询结果返回datatable类型

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SqlHelper
{
    public class ReadRecord
    {
        //获得数据源连接
        public static string connectionString = ConfigurationManager.AppSettings["ConnStr"];
        public static DataTable readrecord(String cmdtxt, CommandType cmdtype, SqlParameter[] paras)
        {
            SqlConnection conn = new SqlConnection(connectionString);
            SqlCommand cmd = default(SqlCommand);
            cmd = new SqlCommand(cmdtxt,conn);
            cmd.CommandType = cmdtype;
            if (paras.Count()>0)
            {
                cmd.Parameters.AddRange(paras); 
            }                        
            DataTable dt=new DataTable ();
            try
            {
                conn.Open();
                SqlDataAdapter sda = new SqlDataAdapter(cmd);  
                sda.Fill(dt);
                return dt;
            }
            catch //Exception e)
            {
                //MessageBox.Show(e.Message);                
                return null;
            }
            finally
            {
                conn.Close();
            }
            
        }
    }
}

二、用于增删改结果返回受影响的行数

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SqlHelper
{
    public class AddDeleteInsert
    {
        //获得数据源连接
        public static string connectionString = ConfigurationManager.AppSettings["ConnStr"];
        public static int adddeleinter(String cmdtxt, CommandType cmdtype, SqlParameter[] paras)
        {
            SqlConnection conn = new SqlConnection(connectionString);
            SqlCommand cmd = default(SqlCommand);
            cmd = new SqlCommand(cmdtxt, conn);
            cmd.CommandType = cmdtype;
            if (paras.Count()>0)
            {
                cmd.Parameters.AddRange(paras);
            }
            try
            {
                conn.Open();
                int adi = cmd.ExecuteNonQuery();
                return adi;
            }
            catch //Exception e)
            {
                //MessageBox.Show(e.Message);
                return -1;
            }
            finally
            {
                conn.Close();
            }
        }
    }
}


阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页