数据库链接:Connection对象

1.概述:

Connection对象是一个链接对象,主要功能是建立与物理数据库的连接。

根据使用的数据库不同,应该引入不同的命名空间。例如对于:
SQL Server数据库,应该引用命名空间 using System.Data.SqlClient。

如下例
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();
}

    private void button1_Click(object sender, EventArgs e)
    {
        if(textBox1 .Text=="")
        {
            MessageBox.Show("请输入要链接的数据库名称");

        }
        else
        {
            try
            {
                //声明一个字符串,用于存储链接数据库字符串;
                string str = "server=.;database=" + textBox1.Text.Trim() + ";uid=sa;pwd=feiche1.16x";//Trim()函数是去掉字符序列左边和右边的空格

                SqlConnection conn = new SqlConnection(str);
                conn.Open();
                if(conn .State ==ConnectionState .Open)
                {
                    label1.Text = "数据库【" + textBox1.Text.Trim() + "】已经连接并打开";
                }
            }
            catch
            {
                MessageBox.Show("数据链接失败");
            }

        }
    }
}

}

(https://blog.csdn.net/zhruifei/article/details/78401729)

猜你喜欢

转载自blog.csdn.net/qq_37855507/article/details/82589911