数据库建立和连接

IDE:

SQL Server Management Studio 用于建立数据库

VS2010:客户端 用于连接数据库 读取内容

注意:

       新建数据库后 ,新建表后。保存 重命名表名后,在对象资源管理器中未找到新建的表。需要:在对象资源管理器中刷新操作

       在安全性的登录名中  点击 sa属性。设置 SQL Server登录验证。修改密码。进入状态 设置登录已启用。确定。保存后,服务器重新启动。

C#连接数据库 查询输出:

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.Data.SqlClient;

namespace CSharp连接数据库
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string strConnection = "Server=user-20160721jz\zzyj;"; //服务器名称
            strConnection += "initial catalog=zyjFirstData;";       //数据库名称
            strConnection += "user id=sa;";//用户
            strConnection += "password=123456;";//密码
            strConnection += "Connect Timeout=5";//连接超时

            bool CanConnectDB = false;
            //实例化一个连接
            using (SqlConnection objConnection = new SqlConnection(strConnection))
            {
                try
                {
                    objConnection.Open();//打开数据库连接
                    CanConnectDB = true;

                    SqlDataAdapter da = new SqlDataAdapter();//实例化sqldataadpter
                    SqlCommand cmd1 = new SqlCommand("select * from 学生", objConnection);//sql语句
                    da.SelectCommand = cmd1;//设置为已实例化SqlDataAdapter的查询命令
                    DataSet ds1 = new DataSet();//实例化dataset
                    da.Fill(ds1);//把数据填充到dataset
                    dataGridView1.DataSource = ds1.Tables[0];//将数据集绑定datagridview,完成显示

                    objConnection.Close();
                }
                catch { }
                if (CanConnectDB)
                {
                    MessageBox.Show("数据库连接成功!", "");
                }
                else
                {
                    MessageBox.Show("数据库连接失败!", "");
                }
            }
        }
    }
}

  

      

原文地址:https://www.cnblogs.com/zhayunjia/p/5733194.html