SQL Server数据库中表的增、删、改、查

通过SqlCommand对象的ExecuteNonQuery方法执行命令行,来实现数据库中表的增、删、改、查。主要有5步

using System.Data.SqlClient;//载入数据库命名空间
        private void button1_Click(object sender, EventArgs e)
        {
            //1、连接数据库
            SqlConnection con = new SqlConnection("Server=CAIWU;User Id=sa;Pwd=;DataBase=db_Me");
            //命令行语句,在表中添加内容。'"+string格式内容+"',"+数字格式内容+"
            string str = "insert into dbo.Table_2(Name,Price) values('"+textBox1.Text+"',"+Convert.ToInt32(textBox2.Text)+")";
            //2、加入命令行语句
            SqlCommand com = new SqlCommand(str, con);
            if (con.State == ConnectionState.Closed)
            {
                con.Open();//3、打开数据库连接
            }//4、SqlCommand对象的ExecuteNonQuery方法执行命令行,并返回受影响的行数
            if (Convert.ToInt32(com.ExecuteNonQuery()) > 0)
            {
                label3.Text = "添加成功!";
            }
            else
            {
                label3.Text = "添加失败!";
            }
            con.Close();//5、关闭数据库连接
        }

     

猜你喜欢

转载自www.cnblogs.com/xixixing/p/10650181.html