在好例子网,分享、交流、成长!
您当前所在位置:首页SQL 开发实例SQL基础 → sql连接测试源码

sql连接测试源码

SQL基础

下载此实例
  • 开发语言:SQL
  • 实例大小:0.08M
  • 下载次数:56
  • 浏览次数:504
  • 发布时间:2018-05-22
  • 实例类别:SQL基础
  • 发 布 人:yrq
  • 文件格式:.rar
  • 所需积分:2
 相关标签: sql 源码 测试

实例介绍

【实例简介】

【实例截图】

from clipboard

【核心代码】

/*
 * Created by SharpDevelop.
 * User: Administrator
 * Date: 2014/5/21
 * Time: 10:12
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
using System.Windows.Forms;

namespace SqlConnectionStringBuilder
{
    /// <summary>
    /// Description of MainForm.
    /// </summary>
    public partial class MainForm : Form
    {
        private System.Data.SqlClient.SqlConnectionStringBuilder sqlConnStr = new System.Data.SqlClient.SqlConnectionStringBuilder() { DataSource = "(local)", IntegratedSecurity = true };
        private SqlConnection cn;
        private DataTable dt;
        private bool isLanguageConnected = false;
        private bool isDatabaseNameConnected = false;

        public MainForm()
        {
            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            InitializeComponent();

            //
            // TODO: Add constructor code after the InitializeComponent() call.
            //
        }

        void MainFormLoad(object sender, EventArgs e)
        {
            //cmbNetworkLibrary.SelectedIndex=0;			
            //cmbSizeUnit.SelectedIndex=0;
            //cmbTimeUnit.SelectedIndex=0;
            txtConnectionString.Text = sqlConnStr.ConnectionString   ";";
        }

        void BtnExitClick(object sender, EventArgs e)
        {
            Application.Exit();
        }

        void BtnCopyClick(object sender, EventArgs e)
        {
            string connString = txtConnectionString.Text.Trim();
            if (connString != string.Empty)
            {
                Clipboard.SetText(connString);
                if (Clipboard.ContainsText())
                    MessageBox.Show("已经复制连接字符串到剪贴板!");
            }
        }

        void BtnTestClick(object sender, EventArgs e)
        {
            Form form = MainForm.ActiveForm;
            form.Enabled = false;
            Thread testConn = new Thread(TestConnection);
            testConn.Start();
            btnTest.Text = "连接测试中";
            testConn.Join();
            form.Enabled = true;
            btnTest.Text = "测试连接";
            form.Show();
        }

        void TestConnection()
        {
            try
            {
                cn = new SqlConnection(sqlConnStr.ConnectionString);
                cn.Open();
                cn.Close();
                MessageBox.Show("连接数据库成功!", "测试连接", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("连接数据库失败!"   ex.ToString(), "测试连接", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void ChkIntegratedCheckedChanged(object sender, EventArgs e)
        {
            txtUserID.Enabled = !chkIntegrated.Checked;
            txtPassword.Enabled = !chkIntegrated.Checked;
            if (chkIntegrated.Checked)
            {
                sqlConnStr.Remove("User ID");
                sqlConnStr.Remove("Password");
                sqlConnStr.IntegratedSecurity = true;
            }
            else
            {
                sqlConnStr.Remove("Integrated Security");
                string UserID = txtUserID.Text.Trim();
                string Password = txtPassword.Text.Trim();
                if (UserID != string.Empty)
                    sqlConnStr.UserID = UserID;
                if (Password != string.Empty)
                    sqlConnStr.Password = Password;
            }
            txtConnectionString.Text = sqlConnStr.ConnectionString   ";";
            isDatabaseNameConnected = false;
            isLanguageConnected = false;
        }

        void CmbNetworkLibrarySelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cmbNetworkLibrary.Text.Trim())
            {
                case "TCP/IP":
                    sqlConnStr.Remove("Network Library");
                    break;
                case "Shared Memory":
                    sqlConnStr.NetworkLibrary = "dbmslpcn";
                    break;
                case "Named Pipes":
                    sqlConnStr.NetworkLibrary = "dbnmpntw";
                    break;
                case "Multiprotocol":
                    sqlConnStr.NetworkLibrary = "dbmsrpcn";
                    break;
                case "Apple Talk":
                    sqlConnStr.NetworkLibrary = "dbmsadsn";
                    break;
                case "VIA":
                    sqlConnStr.NetworkLibrary = "dbmsgnet";
                    break;
                case "IPX/SPX":
                    sqlConnStr.NetworkLibrary = "dbmsspxn";
                    break;
            }
            txtConnectionString.Text = sqlConnStr.ConnectionString   ";";
        }

        void CmbSizeUnitSelectedIndexChanged(object sender, EventArgs e)
        {
            TxtPacketSizeTextChanged(sender, e);
        }

        void CmbTimeUnitSelectedIndexChanged(object sender, EventArgs e)
        {
            TxtTimeOutTextChanged(sender, e);
        }

        void TxtDataSourceTextChanged(object sender, EventArgs e)
        {
            sqlConnStr.DataSource = txtDataSource.Text.Trim();
            if (sqlConnStr.DataSource == string.Empty)
                sqlConnStr.Remove("Data Source");
            txtConnectionString.Text = sqlConnStr.ConnectionString   ";";
            isDatabaseNameConnected = false;
            isLanguageConnected = false;
        }

        void TxtUserIDTextChanged(object sender, EventArgs e)
        {
            sqlConnStr.UserID = txtUserID.Text.Trim();
            if (sqlConnStr.UserID == string.Empty)
                sqlConnStr.Remove("User ID");
            txtConnectionString.Text = sqlConnStr.ConnectionString   ";";
            isDatabaseNameConnected = false;
            isLanguageConnected = false;
        }

        void TxtPasswordTextChanged(object sender, EventArgs e)
        {
            sqlConnStr.Password = txtPassword.Text.Trim();
            if (sqlConnStr.Password == string.Empty)
                sqlConnStr.Remove("Password");
            txtConnectionString.Text = sqlConnStr.ConnectionString   ";";
            isDatabaseNameConnected = false;
            isLanguageConnected = false;
        }

        void CmbDatabaseNameSelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbDatabaseName.Items.Count > 0)
            {
                if (cmbDatabaseName.Text == string.Empty)
                    sqlConnStr.Remove("Initial Catalog");
                else
                    sqlConnStr.InitialCatalog = cmbDatabaseName.Text;
                txtConnectionString.Text = sqlConnStr.ConnectionString   ";";
            }
        }

        void TxtInitialFileNameTextChanged(object sender, EventArgs e)
        {
            sqlConnStr.AttachDBFilename = txtInitialFileName.Text.Trim();
            if (sqlConnStr.AttachDBFilename == string.Empty)
                sqlConnStr.Remove("AttachDBFilename");
            txtConnectionString.Text = sqlConnStr.ConnectionString   ";";
        }

        void ChkPersistSecurityInfoCheckedChanged(object sender, EventArgs e)
        {
            sqlConnStr.PersistSecurityInfo = chkPersistSecurityInfo.Checked;
            if (!sqlConnStr.PersistSecurityInfo)
                sqlConnStr.Remove("PersistSecurityInfo");
            txtConnectionString.Text = sqlConnStr.ConnectionString   ";";
        }

        void ChkEncryptCheckedChanged(object sender, EventArgs e)
        {
            sqlConnStr.Encrypt = chkEncrypt.Checked;
            if (!sqlConnStr.Encrypt)
                sqlConnStr.Remove("Encrypt");
            txtConnectionString.Text = sqlConnStr.ConnectionString   ";";
        }

        void ChkPoolingCheckedChanged(object sender, EventArgs e)
        {
            sqlConnStr.Pooling = chkPooling.Checked;
            if (sqlConnStr.Pooling)
                sqlConnStr.Remove("Pooling");
            txtConnectionString.Text = sqlConnStr.ConnectionString   ";";
        }

        void ChkResetCheckedChanged(object sender, EventArgs e)
        {
            sqlConnStr.ConnectionReset = chkReset.Checked;
            if (sqlConnStr.ConnectionReset)
                sqlConnStr.Remove("Connection Reset");
            txtConnectionString.Text = sqlConnStr.ConnectionString   ";";
        }

        void ChkEnlistCheckedChanged(object sender, EventArgs e)
        {
            sqlConnStr.Enlist = chkEnlist.Checked;
            if (sqlConnStr.Enlist)
                sqlConnStr.Remove("Enlist");
            txtConnectionString.Text = sqlConnStr.ConnectionString   ";";
        }

        void TxtConnectionLifetimeTextChanged(object sender, EventArgs e)
        {
            int connectionLifetime = 0;
            if (txtConnectionLifetime.Text.Length > 0)
                connectionLifetime = Int32.Parse(txtConnectionLifetime.Text);
            if (connectionLifetime == 0)
                sqlConnStr.Remove("Load Balance Timeout");
            else
                sqlConnStr.LoadBalanceTimeout = connectionLifetime;
            txtConnectionString.Text = sqlConnStr.ConnectionString   ";";
        }

        void TxtConnectionLifetimeKeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar) || e.KeyChar == '\b') || (txtConnectionLifetime.Text.Length == 2 && e.KeyChar != '\b'))
                e.Handled = true;
        }

        void TxtMinPoolSizeTextChanged(object sender, System.EventArgs e)
        {
            int MinPoolSize = 0;
            if (txtMinPoolSize.Text.Length > 0)
                MinPoolSize = Int32.Parse(txtMinPoolSize.Text);
            if (MinPoolSize == 0)
                sqlConnStr.Remove("Min Pool Size");
            else
                sqlConnStr.MinPoolSize = MinPoolSize;
            txtConnectionString.Text = sqlConnStr.ConnectionString   ";";
        }

        void TxtMaxPoolSizeTextChanged(object sender, EventArgs e)
        {
            int MaxPoolSize = 0;
            if (txtMaxPoolSize.Text.Length > 0)
                MaxPoolSize = Int32.Parse(txtMaxPoolSize.Text);
            if (MaxPoolSize == 0)
                sqlConnStr.Remove("Max Pool Size");
            else
                sqlConnStr.MaxPoolSize = MaxPoolSize;
            txtConnectionString.Text = sqlConnStr.ConnectionString   ";";
        }

        void TxtMaxPoolSizeKeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar) || e.KeyChar == '\b') || (txtMaxPoolSize.Text.Length == 5 && e.KeyChar != '\b'))
                e.Handled = true;
        }

        void TxtMinPoolSizeKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar) || e.KeyChar == '\b') || (txtMinPoolSize.Text.Length == 5 && e.KeyChar != '\b'))
                e.Handled = true;
        }

        void TxtPacketSizeTextChanged(object sender, EventArgs e)
        {
            int PacketSize = 0;
            if (txtPacketSize.Text.Length > 0)
            {
                PacketSize = Int32.Parse(txtPacketSize.Text);
                if (cmbSizeUnit.Text == "KB")
                    PacketSize *= 1024;
                if (PacketSize >= 512 && PacketSize <= 32768)
                    sqlConnStr.PacketSize = PacketSize;
                else
                    PacketSize = 0;
            }
            if (txtPacketSize.Text.Length == 0 || PacketSize == 0 || sqlConnStr.PacketSize == 8192)
                sqlConnStr.Remove("Packet Size");
            txtConnectionString.Text = sqlConnStr.ConnectionString   ";";
        }

        void TxtTimeOutTextChanged(object sender, System.EventArgs e)
        {
            if (txtTimeOut.Text.Length > 0)
                sqlConnStr.ConnectTimeout = Int32.Parse(txtTimeOut.Text);
            if (cmbTimeUnit.Text == "分钟")
                sqlConnStr.ConnectTimeout *= 60;
            if (txtTimeOut.Text.Length == 0 || sqlConnStr.ConnectTimeout == 0 || sqlConnStr.ConnectTimeout == 15)
                sqlConnStr.Remove("ConnectTimeout");
            txtConnectionString.Text = sqlConnStr.ConnectionString   ";";
        }

        void TxtPacketSizeKeyPress(object sender, KeyPressEventArgs e)
        {
            if (txtPacketSize.SelectionLength == 0 && (!(Char.IsNumber(e.KeyChar) || e.KeyChar == '\b') || (txtPacketSize.Text.Length == 5 && e.KeyChar != '\b')))
                e.Handled = true;
        }

        void TxtTimeOutKeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar) || e.KeyChar == '\b') || (txtTimeOut.Text.Length == 2 && e.KeyChar != '\b'))
                e.Handled = true;
        }

        void TxtWorkstationIDTextChanged(object sender, EventArgs e)
        {
            sqlConnStr.WorkstationID = txtWorkstationID.Text.Trim();
            if (sqlConnStr.WorkstationID == string.Empty)
                sqlConnStr.Remove("Workstation ID");
            txtConnectionString.Text = sqlConnStr.ConnectionString   ";";
        }

        void TxtApplicationNameTextChanged(object sender, EventArgs e)
        {
            sqlConnStr.ApplicationName = txtApplicationName.Text.Trim();
            if (sqlConnStr.ApplicationName == string.Empty || sqlConnStr.ApplicationName == ".Net SqlClient Data Provider")
                sqlConnStr.Remove("Application Name");
            txtConnectionString.Text = sqlConnStr.ConnectionString   ";";
        }

        void CmbDatabaseNameClick(object sender, EventArgs e)
        {
            if (!isDatabaseNameConnected)
            {
                try
                {
                    Thread thDatabaseNames = new Thread(GetDatabaseNames);
                    thDatabaseNames.Start();
                    btnExit.Enabled = btnCopy.Enabled = btnTest.Enabled = false;
                    btnTest.Text = "连接数据库中";
                    thDatabaseNames.Join();
                    btnExit.Enabled = btnCopy.Enabled = btnTest.Enabled = true;
                    btnTest.Text = "测试连接";
                    cmbDatabaseName.DataSource = dt;
                    isDatabaseNameConnected = true;
                }
                catch (Exception)
                {
                    MessageBox.Show("连接数据库失败!", "获取数据库", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        void GetDatabaseNames()
        {
            try
            {
                cn = new SqlConnection(sqlConnStr.ConnectionString);
                cn.Open();
                dt = cn.GetSchema("Databases");
                cn.Close();
                DataRow dr = dt.NewRow();
                dt.Rows.InsertAt(dr, 0);
            }
            catch (Exception)
            {

            }
        }

        void CmbLanguageSelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbLanguage.Items.Count > 0)
            {
                if (cmbLanguage.Text == string.Empty)
                    sqlConnStr.Remove("Current Language");
                else
                    sqlConnStr.CurrentLanguage = cmbLanguage.Text;
                txtConnectionString.Text = sqlConnStr.ConnectionString   ";";
            }
        }

        void CmbLanguageClick(object sender, EventArgs e)
        {
            if (!isLanguageConnected)
            {
                try
                {
                    Thread thDatabaseLanguages = new Thread(GetDatabaseLanguages);
                    thDatabaseLanguages.Start();
                    btnExit.Enabled = btnCopy.Enabled = btnTest.Enabled = false;
                    btnTest.Text = "连接数据库中";
                    thDatabaseLanguages.Join();
                    btnExit.Enabled = btnCopy.Enabled = btnTest.Enabled = true;
                    btnTest.Text = "测试连接";
                    cmbLanguage.DataSource = dt;
                    isLanguageConnected = true;
                }
                catch (Exception)
                {
                    MessageBox.Show("连接数据库失败!", "获取数据库语言", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        void GetDatabaseLanguages()
        {
            try
            {
                cn = new SqlConnection(sqlConnStr.ConnectionString);
                cn.Open();
                dt = new DataTable();
                new SqlDataAdapter(new SqlCommand("exec sp_helplanguage", cn)).Fill(dt);
                cn.Close();
                DataRow dr = dt.NewRow();
                dt.Rows.InsertAt(dr, 0);
            }
            catch (Exception)
            {

            }
        }
    }
}

标签: sql 源码 测试

实例下载地址

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警