第二周学习笔记

 

第二周学习笔记

SqlConnection对象

要连接SQL Sever数据库,就要使用System.Data.SqlClient命令空间下的SqlConnection类。

首先要通过using System.DataSqlClient命令引用命令空间,连接数据库之后,通过调用SqlConnection对象的Open方法打开数据库。

通过SqlConnection对象的State属性判断数据库的连接状态:

 

Public override ConnectionState State {get;}

连接数据库:(连接代码)

Windows连接代码如下:

sqlConnection.ConnectionString=”Server=(Local);Database=EduBaseDemo;Integrated Security=sspi”;

打开关闭数据库;

SqlConnection.Open();

SqlConnection.Close();

 

 

连接数据库实例:

 private void butt_connecting_Click(object sender, EventArgs e)

        {

            if (textBox1.Text == "")

            {

                MessageBox.Show("请输入数据库名称");

            }

            else

            {

                try

                {

                    string ConStr = "server=.;database=" + textBox1.Text.Trim() + ";uid=sa;pwd=";

                    SqlConnection conn = new SqlConnection(ConStr);

                    conn.Open();

                    if (conn.State == Connection.Open)

                    {

                        label2.Text = "数据库[" + textBox1.Text.Trim() + "]已经连接并打开";

                    }

                }

                catch

                {

                    MessageBox.Show("数据库连接失败");

                }

            }

        }

 

SqlCommand对象

SqlCommand对象用于执行具体的SQL语句,如增加、删除、修改、查找。

Command对象有3个重要属性,分别是Connection属性、CommandText属性和CommandType属性。Connection属性用于设置SqlCommand使用的SqlConnection。CommandText属性用于设置要对数据源执行的SQL语句或存储过程。CommandType属性用于设置指定的CommandText的类型。如果要设置数据源的类型,便可以通过设置CommandType属性来实现。

 

执行SQL语句,并返回首影响行数,通常使用ExecuteNonQuery方法执行,返回值:受影响的行数。

语法如下:

Public override int ExecuteNonQuery()

 

执行SQL语句,并生成一个包含数据的SqlDataReader对象的实例,返回值:一个SqlDataReader对象。

语法如下:

Public SqlDataReader ExecuteReader()

 

执行SQL语句,返回结果集中的第一行的第一列。

语法如下:

Public override Object ExecuteScalar()

 

 

SqlCommand对象查询实例:

        private void inquire_Load(object sender, EventArgs e)

        {

            SqlConnection conn = new SqlConnection();

            conn=new SqlConnection("sever=.;database=db_1;Integrated Security=sspi");

            conn.Open();

        }

 

        private void searching_Click(object sender, EventArgs e)

        {

            try

            {

                if (conn.State == ConnectionState.Open||textBox1.Text!="")

                {

                    SqlCommand cmd = new SqlCommand();

                    cmd.Connection = conn;

                    cmd.CommandText = "slect count(*)from" + textBox1.Text.Trim();

                    cmd.CommandType = CommandType.Text;

                    int i = Convert.ToInt32(cmd.ExecuteScalar());

                    label2.Text = "数据表*有:" + i.ToString() + "条数据";

 

                }

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

        }