c#中访问数据库的sqlCommand的几种方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40245756/article/details/79919817

在建立了连接后

//以下分别为在个人电脑与机房的链接区别
            string connectionString = @"Data Source = TAOR\TAOR; Initial Catalog = 01; Integrated Security = True";
            //string connectionString = "Data Source=.;Initial Catalog=02.车辆;Integrated Security=True";
            conn = new SqlConnection(connectionString);
有三种方式来执行建立sqlCommand
//以下为示例代码内容
            conn.Open();

            /*//命令方法一:
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = "insert into student values(2,'李四',18,'女')";//数据库中的字符串必须是用‘’引住
            */

            /*//命令方法二:
            string sql = "insert into student values(2,'李四',18,'女')";
            SqlCommand cmd = new SqlCommand(sql, conn);
            */

            //命令方法三:
            SqlCommand cmd = conn.CreateCommand();
            string sql = "insert into student values(2,'李四',18,'女')";
            cmd.CommandText = sql;

            int n = cmd.ExecuteNonQuery();//对连接执行命令并返回受影响行数
            MessageBox.Show("成功加入" + n + "条记录!");

            conn.Close();


此外,要注意CommandText中引号的使用

例:

cmd_1.CommandText = "insert into student values('"+Convert.ToInt32(textBox1.Text)+"','"+textBox2.Text+"','"+Convert.ToInt32(textBox4.Text)+"','"+textBox3.Text+"')";
            //此处注意''和""的使用,字符串类型在输入时必须加上''
            //还要注意+号的使用

猜你喜欢

转载自blog.csdn.net/qq_40245756/article/details/79919817