C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > c#测试本机sql运算速度

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

作者:

本文代码目的很简单,就是使用c#测试一下本机sql运算的速度,使用循环往数据里大量插入数据,计算所用时间,大家参考使用吧

复制代码 代码如下:

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

您可能感兴趣的文章:
阅读全文