예제 #1
0
        //带参数的插入1
        public static int test_insertCmdwithParams()
        {
            XGConnection conn = new XGConnection();

            conn.ConnectionString = conn_xg;

            try
            {
                conn.Open();
                XGCommand cmd = new XGCommand();
                cmd.Connection = conn;
                string sql = "insert into tp(pid,pname) values(?,?)";

                cmd.CommandText = sql;

                XGTransaction trans = conn.BeginTransaction(); //为连接创建显示事务,此时该连接事务处于非自动提交状态
                cmd.Transaction = trans;                       //指定申明命令事务环境

                //参数赋值
                cmd.Parameters.Add("pid", XGDbType.Int).Value       = 2;
                cmd.Parameters.Add("pname", XGDbType.VarChar).Value = "开发部";
                cmd.ExecuteNonQuery();

                //重复执行参数赋值前,需清除前次参数
                cmd.Parameters.Clear();

                //采用AddWithValue方法
                object t_int = 3;
                object t_str = "测试部";
                cmd.Parameters.AddWithValue("pid", t_int);
                cmd.Parameters.AddWithValue("pname", t_str);

                //采用AddRange方法
                cmd.Parameters.Clear();
                XGParameters[] t_Arr = new XGParameters[2];
                t_Arr[0]       = new XGParameters("pid", XGDbType.Int);
                t_Arr[0].Value = 4;
                t_Arr[1]       = new XGParameters("pname", XGDbType.VarChar);
                t_Arr[1].Value = "产品部";
                cmd.Parameters.AddRange(t_Arr);


                cmd.ExecuteNonQuery();

                trans.Commit();//提交命令事务

                //free cmd and disconnect
                cmd.Dispose();
                conn.Close();
                return(0);
            }
            catch (Exception Err)
            {
                Console.WriteLine("Error :");
                Console.WriteLine("\t{0}", Err.ToString());
                conn.Close();
                return(-1);
            }
        }