using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace 连接数据库方式
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.CenterToScreen();
this.txtUserID.Enabled = false; //可用性关闭
this.txtUserPWD.Enabled = false;
}
private void btnQuit_Click(object sender, EventArgs e)
{
this.Close(); //关闭改窗体
}
private void btConnect_Click(object sender, EventArgs e)
{
if (this.txtServerName.TextLength==0)
{
MessageBox.Show("服务器名输入不能为空!","输入提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
this.txtServerName.Focus(); //获得焦点
return;
}
string strServerName = txtServerName.Text.Trim();
if (this.txtDBName.TextLength==0)
{
MessageBox.Show("数据库名不能为空!","输入提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
this.txtDBName.Focus();
return;
}
string strDBName = txtDBName.Text.Trim(); //去除字符串前后的
string strUserID = txtUserID.Text.Trim();
SqlConnectionStringBuilder builder=new SqlConnectionStringBuilder(); //创建连接字符串创创造器
string strPWD = txtUserPWD.Text.Trim();
if (this.radioWindows.Checked==true) //判断单选框是否被选择
{
builder.IntegratedSecurity = true;
builder.DataSource = @strServerName;
builder.InitialCatalog = strDBName;
}
else
{
if (this.txtUserID.TextLength==0)
{
MessageBox.Show("用户名输入不能为空!","输入提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
this.txtUserID.Focus();
return;
}
builder.DataSource = @strServerName; //前面@作用:DESKTOP-UJ5IEQK\THIRTEEN 这样的服务器(实例)名称中间的“\”能够被转义 ;另一种方法:中间吧“\”变为“\\”
builder.InitialCatalog = strDBName;
builder.UserID = strUserID;
builder.Password = strPWD;
}
SqlConnection conn = new SqlConnection();
conn.ConnectionString = builder.ConnectionString; //嫁接字符串
try
{
conn.Open();
}
catch (SqlException sqlE)
{
MessageBox.Show(sqlE.Message, "连接提示", MessageBoxButtons.OK,MessageBoxIcon.Information);
return;
}
MessageBox.Show("成功登录数据库!", "连接提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void radioWindows_CheckedChanged(object sender, EventArgs e)
{
this.txtUserID.Enabled = false;
this.txtUserPWD.Enabled = false;
}
private void radioSql_CheckedChanged(object sender, EventArgs e)
{
this.txtUserID.Enabled = true;
this.txtUserPWD.Enabled = true;
}
}
}
连接数据库方式
最新推荐文章于 2022-03-21 13:45:47 发布