C#:01数据库连接

这篇博客介绍了如何使用C#连接(localdb)MSSQLLocalDB数据库,包括连接字符串的设置和Windows身份验证。重点讲解了DataReader对象,它是只读数据集,适用于检索大量数据,并列举了相关属性和方法。还提到了Command命令执行对象以及如何通过循环显示所有行和列的数据。

 

使用VS2015自带的  (localdb)\MSSQLLocalDB  或者  (localdb)\ProjectsV13,这是mini版的数据库系统,大概几十兆大小,在连接字符串中,它俩作为服务器的名字和默认实例。

连接字符串:

string constr = "server=(localdb)\\MSSQLLocalDB;Initial Catalog=Test;Integrated Security=true;";
string constr = "Data Source=(localdb)\\MSSQLLocalDB;database=Test;Integrated Security=sspi;";

server等价于Data Source,指定服务器;

Initial Catalog等价于database:指定哪一个数据库

Integrated Security是Windows登陆验证方式,=true或者=SSPI是等价的

如果我们放置一个按钮button1,点击按钮就连接数据库的话,则在按钮的点击事件中有:

 Windows 身份验证模式:Integrated Security=true

        private void button1_Click(object sender, EventArgs e)
        {


            try
            {
                //string constr = "server=(localdb)\\MSSQLLocalDB;Initial Catalog=Test;Integrated Security=true";
                string constr = "Data Source=(localdb)\\MSSQLLocalDB;database=Test;Integrated Security=true";
                SqlConnection conn = new SqlConnection(constr);//1、创建连接对象conn
                conn.Open();        //2、打开方法
                if (conn.State == ConnectionState.Open) // 通过state字段判断是否连接成功
                {
                    label1.Text = "数据库打开成功";
                }
                conn.Close();
                if(conn.State==ConnectionState.Closed)
                {
                    label2.Text = "数据库关闭成功"; ;
                }
            }
            catch   //通过异常来处理打不开数据库的情况
            {
                MessageBox.Show("数据库打开失败");
            }
        }

SQL Server方式登录uid=sa;pwd= 

user id 或者password

右键(localdb)\MSSQLLocalDB 新建如下查询,可设置sa用户生效,sa是超级管理员:super administrator

ALTER LOGIN sa ENABLE ;  
GO  
ALTER LOGIN sa WITH PASSWORD = '' ;  
GO

        private void button1_Click(object sender, EventArgs e)
        {


            try
            {
                string constr = "Data Source=(localdb)\\MSSQLLocalDB;database=Test;uid=sa;pwd=";
                SqlConnection conn = new SqlConnection(constr);//1、创建连接对象conn
                conn.Open();        //2、打开方法
                if (conn.State == ConnectionState.Open) // 通过state字段判断是否连接成功
                {
                    label1.Text = "数据库打开成功";
                }
                conn.Close();
                if(conn.State==ConnectionState.Closed)
                {
                    label2.Text = "数据库关闭成功"; ;
                }
            }
            catch   //通过异常来处理打不开数据库的情况
            {
                MessageBox.Show("数据库打开失败");
            }
        }

DataReader对象概述

       DataReader对象是一个简单的数据集,它主要用于从数据源中读取只读的数据集,其常用于检索大量数据使用DataReader对象读取数据时,必须一直保持与数据库的连接,所以也被称为连线模式

DataReader的属性和方法:

属性

说明

HasRows

判断数据库中是否有数据

FieldCount

获取当前行的列数

RecordsAffected

获取执行SQL语句所更改、添加或删除的行数

方法

说明

Read

使DataReader对象前进到下一条记录

Close

关闭DataReader对象

Get

用来读取数据集的当前行的某一列的数据

Command命令执行对象

DataReader数据读取对象

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _02_显示数据库的数据
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string constr = "Data Source=cnh-server;database=NorthWind_CH;Integrated Security=true";
            SqlConnection conn = new SqlConnection(constr);//1、创建连接对象conn

            string sql = "select * from 产品";
            SqlCommand cmd = new SqlCommand(sql, conn);//2、创建sqlcommand对象

            conn.Open();        //调用open方法

            //3、调用ExecuteReader()方法,将给定的sql语句在服务器执行
            //执行完毕后,数据库服务器就已经查询出数据。但是数据保存在数据库服务器的内存中
            //并没有返回给应用程序。只是给应用程序一个reader对象,通过这个对象获取数据库服务器的内存中的数据
            SqlDataReader reader = cmd.ExecuteReader();
            richTextBox1.Text = "产品ID\t产品名称\n";

            try
            {
                if (conn.State == ConnectionState.Open) // 通过state字段判断是否连接成功
                {
                    label1.Text = "数据库连接成功";

                    
                    //获取数据是一条一条获取的,获取之前先判断下本次是否查询到数据
                    if (reader.HasRows)//如果有数据,值为ture,否则值为false
                    {
                        //如果有数据,则每次读取一条,读取完毕,跳转到下一条,读到最后为空,即false结束
                        while (reader.Read())
                        {
                            //可通过索引的方式获取列的值:reader["属性名称"]
                            richTextBox1.Text += reader["产品id"] + "\t" + reader["产品名称"] + "\n";
                        }
                    }
                }
            }

            catch(SqlException ex)   //通过异常来处理打不开数据库的情况
            {
                MessageBox.Show(ex.ToString());
            }

            finally
            {
                reader.Close();
                conn.Close();
                if (conn.State == ConnectionState.Closed)
                {
                    label2.Text = "数据库连接关闭";
                }
            }
        }
    }
}

改为通过循环显示所有行和列的数据

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _03_显示数据库的表中所有的属性
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string constr = "Data Source=cnh-server;database=NorthWind_CH;Integrated Security=true";
            SqlConnection conn = new SqlConnection(constr);//1、创建连接对象conn

            string sql = "select * from 产品";
            SqlCommand cmd = new SqlCommand(sql, conn);//2、创建sqlcommand对象

            conn.Open();        //调用open方法

            //3、调用ExecuteReader()方法,将给定的sql语句在服务器执行
            //执行完毕后,数据库服务器就已经查询出数据。但是数据保存在数据库服务器的内存中
            //并没有返回给应用程序。只是给应用程序一个reader对象,通过这个对象获取数据库服务器的内存中的数据
            SqlDataReader reader = cmd.ExecuteReader();
            richTextBox1.Text = "产品ID\t产品名称 供应商Id 类别ID 单位数量\t单价\t库存量\t订购量\t再订购量 中止\n";

            try
            {
                if (conn.State == ConnectionState.Open) // 通过state字段判断是否连接成功
                {
                    label1.Text = "数据库连接成功";


                    //获取数据是一条一条获取的,获取之前先判断下本次是否查询到数据
                    if (reader.HasRows)//如果有数据,值为ture,否则值为false
                    {
                        //如果有数据,则每次读取一条,读取完毕,跳转到下一条,读到最后为空,即false结束
                        while (reader.Read())
                        {
                            //FileCount是列的个数,即一共几列
                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                richTextBox1.Text += reader[i].ToString()+"\t";
                            }
                            richTextBox1.Text += "\n";
                        }
                    }
                }
            }

            catch (SqlException ex)   //通过异常来处理打不开数据库的情况
            {
                MessageBox.Show(ex.ToString());
            }

            finally
            {
                reader.Close();
                conn.Close();
                if (conn.State == ConnectionState.Closed)
                {
                    label2.Text = "数据库连接关闭";
                }
            }
        }
    }
}

使用数据库登录

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _04_用户登录
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //1、采集数据
            string logname = textBox1.Text.Trim();
            string logpwd = textBox2.Text;

            //2、连接数据库
            string constr = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=E:\C#教学\用户登录.mdf;Integrated Security=True";
            using (SqlConnection con = new SqlConnection(constr))
            {
                string sql =string.Format("select count(*) from 用户名密码表 where username='{0}' and userpassword='{1}'", logname, logpwd);
                using (SqlCommand cmd = new SqlCommand(sql, con))
                {
                    con.Open();
                    if (con.State == ConnectionState.Open)
                    {
                        
                        MessageBox.Show("数据库连接成功!");

                        int count = (int)cmd.ExecuteScalar();
                        if (count > 0)
                        {
                            MessageBox.Show("登录成功");
                        }
                        else
                        {
                            MessageBox.Show("登录失败");
                        }
                    }
                    else
                    {
                        MessageBox.Show("数据库连接失败!");
                    }
                }
            }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值