c#测试本机sql运算速度的代码示例分享

 更新时间:2020年6月25日 11:38  点击:1753

复制代码 代码如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            SqlConnection conn = new SqlConnection();
            SqlCommand comm = new SqlCommand();
            DateTime t1, t2;
            int count = 10000;  //循环次数
            string times;
            conn.ConnectionString = "Data Source=.;Initial Catalog=Server;Integrated Security=True";
            comm.CommandText = "insert into test (Cid,Cvalue) values('1','1')"; //数据插入
            comm.Connection = conn;
            Console.WriteLine("开始插入数据\r\n开始时间:" +(t1=DateTime.Now).ToLongTimeString());
            try
            {
                conn.Open();
                for (int i = 1; i <= count; i++)
                {
                    comm.ExecuteNonQuery(); //执行查询
                }
                Console.WriteLine("结束时间:" + (t2 = DateTime.Now).ToLongTimeString());
                times = GetTimeSpan(t1, t2).ToString();
                Console.WriteLine("持续时间:" + times.Substring(0, times.LastIndexOf(".") + 4));
                Console.WriteLine("本次测试总共对数据库进行了" + count + "次数据插入操作!");
                //comm.CommandText = "delete from test";
                //comm.ExecuteNonQuery();
                //Console.WriteLine("测试数据已删除");
            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
            }
            finally
            {
                comm = null;
                conn.Close();
                conn.Close();
            }
            Console.ReadKey();
        }

        /// <summary>
        /// 返回两个时间对象的时间间隔
        /// </summary>
        private static TimeSpan GetTimeSpan(DateTime t1, DateTime t2)
        {
            DateTime t3;
            if (DateTime.Compare(t1, t2) == 1)
            {
                t3 = t1;
                t1 = t2;
                t2 = t3;
            }
            return t2.Subtract(t1);
        }
    }
}

[!--infotagslink--]

相关文章