Csharp连接sql server数据库
1,需要引用system.data.sqlclent命名空间
using System.Data.SqlClient;
2,通过sql server验证连接到服务器:
连接数据库需要明确数据库连接字符串,为固定格式:"server={服务器名称};database={数据库名称};uid=sa;pwd="
新建并实例化一个sqlConnection对象,使用:public SqlConnection(string connectionString)构造函数
使用sqlConnection.open(),打开数据库
使用连接属性判断sqlConnection.state == sqlConnection.open ,可判断当前数据库连接
ConnectionState的枚举值
{ broken=0x10 //与数据源连接中断
closed=0//连接关闭状态
connecting=2 //正在连接数据库
open=1 //连接打开状态
executing=4 //连接对象正在执行命令
fetching=8 //连接对象正在检索数据}
``
点击查看代码
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("请输入要连接的数据库名称");
}
else
{
try
{ //1.数据库连接字符串
//数据库连接字符串相当如打开数据库的钥匙,其格式为:
//Server = 服务器名; Database = 数据库名; uid = 用户名; pwd = 密码; Trusted_Connection = False;
//其中,如果是本机运行的Sqlserver,Server可以使用“.”,“localhost”,“127.0.0.1”
//Trusted_Connection = False; 不采用信任连接方式(也即不采用Windows验证方式),而改由SQL Server 2000验证方式
//假设我的数据库安装在本机,需要使用的数据库为Session1,用户为sa,密码为qwer,则数据库连接字符串就可以设置为:
//Server = localhost; Database = Session1; uid = sa; pwd = qwer; Trusted_Connection = False;
//————————————————
//这里是被南宫问雅摸了虾头!
//原文链接:https://blog.csdn.net/weixin_59249304/article/details/127321339
string ConStr = "Server=LAPTOP-8QNP49PK;database=" + textBox1.Text.Trim() + ";uid=sa;pwd=";
SqlConnection conn = new SqlConnection(ConStr);
conn.Open();
if (conn.State == ConnectionState.Open)
{
label2.Text = "数据库【" + textBox1.Text.Trim() + "】已经连接并打开";
}
}
catch
{
MessageBox.Show("连接数据库失败");
}
}
}

浙公网安备 33010602011771号