using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class SetDB : Form
{
public SetDB()
{
InitializeComponent();
}
/// <summary>
/// 连接测试是否成功
/// </summary>
public bool isConnect { get; set; }
private void frmDb_Load(object sender, EventArgs e)
{
this.CenterToParent();
}
private void button1_Click(object sender, EventArgs e)
{
//将得到配置值传给主安装程序类
string serverName = textBox1.Text.Trim();
string dbName = textBox2.Text.Trim();
string userName = textBox3.Text.Trim();
string password = textBox4.Text.Trim();
isConnect = TestConnection(serverName, dbName, userName, password);//测试连接,此处调用其它类中的代码。
if (isConnect == true)
{
label5.Text = "数据库连接测试成功!";
button2.Enabled = true;
}
else
{
button2.Enabled = false;
label5.Text = "数据库连接测试失败!";
}
}
/// <summary>
/// 测试连接
/// </summary>
/// <param name="serverName"></param>
/// <param name="dbName"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
private bool TestConnection(string serverName, string dbName, string userName, string password)
{
string connectionString = GetConnectionString(serverName, dbName, userName, password);
SqlConnection connection = new SqlConnection(connectionString);
try
{
if (connection.State != ConnectionState.Open)
{
connection.Open();
}
return true;
}
catch
{
CloseConnection(connection);
return false;
}
}
/// <summary>
/// 得到连接字符串
/// </summary>
/// <param name="serverName"></param>
/// <param name="dbName"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <returns></returns>
private string GetConnectionString(string serverName, string dbName, string userName, string password)
{
string connectionString = "server={0};database={1};uid={2};pwd={3}";
connectionString = string.Format(connectionString, serverName, dbName, userName, password);
return connectionString;
}
/// <summary>
/// 关闭数据库
/// </summary>
/// <param name="connection"></param>
private void CloseConnection(SqlConnection connection)
{
if (connection != null)
{
//关闭数据库
if (connection.State != System.Data.ConnectionState.Closed)
{
connection.Close();
connection.Dispose();
}
}
}
}
}