c#中带参数sql查询

System.Data.SqlClient.SqlParameter[] parameters = {
                    new SqlParameter("@Model_GUID", SqlDbType.UniqueIdentifier),
                    new SqlParameter("@Model_Name", SqlDbType.NVarChar,50),
                    new SqlParameter("@Model_Desp", SqlDbType.NVarChar,500),
                    new SqlParameter("@Model_IsSys", SqlDbType.Bit)
            };
            parameters[0].Value = new Guid("F3CD1369-58C0-4A1F-AF88-05FCF734E079");
            parameters[1].Value = "测试实体模型";
            parameters[2].Value = "实体模型描述";
            parameters[3].Value = false;



            string connStr = @"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=officially;Data Source=LCSNB"SQL2K";
            string cmdStr = "insert into LCS_Sys_Model ([Model_GUID],[Model_Name],[Model_Desp],[Model_IsSys]) values ( @Model_GUID,@Model_Name,@Model_Desp,@Model_IsSys)";

            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connStr);
            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(cmdStr);

            cmd.Connection = conn;
            foreach (var item in parameters)
            {
                cmd.Parameters.Add(item);
            }


            cmd.Connection.Open();
            cmd.ExecuteNonQuery();
            //第一次执行结束
            cmd.Parameters.Clear();
            cmd.CommandText = "SELECT SCOPE_IDENTITY()";

            //System.Diagnostics.Debug.Assert(cmd.ExecuteScalar()==null);

            Console.WriteLine(cmd.ExecuteScalar().ToString());
            //第二次执行结束
            cmd.Connection.Close();

            Console.WriteLine("第一次测试结束");
            Console.Read();

            cmd.CommandText = "insert into lcs_Sys_Model ([Model_GUID],[Model_Name],[Model_Desp],[Model_IsSys]) values ( 'F3CD1369-58C0-4A1F-AF88-05FCF734E079','name','desp',1 )";
            cmd.Connection.Open();
            cmd.ExecuteNonQuery();
           
            cmd.CommandText = "SELECT SCOPE_IDENTITY()";
            Console.WriteLine(cmd.ExecuteScalar().ToString());
            cmd.Connection.Close();
            Console.WriteLine("第二次测试结束");
            Console.Read();

 

你可能感兴趣的:(sql,String,Security,C#,insert,Parameters)