日期:2014-05-18  浏览次数:20846 次

SqlParameter怎么不能带单引号
C# code
//参数sql语句写法
                //SqlParameter[] paras =
                //{new SqlParameter("@username",SqlDbType.NVarChar),
                // new SqlParameter("@ip",SqlDbType.NVarChar),
                // new SqlParameter("@time",SqlDbType.DateTime),
                // new SqlParameter("@logstate",SqlDbType.Bit),
                // new SqlParameter ("@illegal",SqlDbType.Bit),
                //};
                //paras[0].Value = username;
                //paras[1].Value = ip;
                //paras[2].Value = time;
                //paras[3].Value = logstate;
                //paras[4].Value = illegal;
                //string sqlcmd = "insert into User_Log (用户名,ip,登陆时间,在线状态,非法登陆) values "+"(" +@username + "," +@ip+ "," +@time+ "," +@logstate+ "," +@illegal+")" ;
                
                SqlCommand cmd = new SqlCommand(sqlcmd, conn);
                
                //cmd.Parameters.Add(paras[0]);
                //cmd.Parameters.Add(paras[1]);
                //cmd.Parameters.Add(paras[2]);
                //cmd.Parameters.Add(paras[3]);
                //cmd.Parameters.Add(paras[4]);

哪里写错了吗?sqlcmd的写法对不对。
另外,如果我用:
 
C# code
//foreach (SqlParameter i in paras)
                //{
                //    cmd.Parameters.Add(paras);
                //}

就要报错,该怎么写

------解决方案--------------------
C# code
string sqlcmd = "insert into User_Log (用户名,ip,登陆时间,在线状态,非法登陆) values(@username,@ip,@time,@logstate,@illegal)" ;

------解决方案--------------------
C# code

//参数sql语句写法
                SqlParameter[] paras =
                {new SqlParameter("@username",SqlDbType.NVarChar),
                 new SqlParameter("@ip",SqlDbType.NVarChar),
                 new SqlParameter("@time",SqlDbType.DateTime),
                 new SqlParameter("@logstate",SqlDbType.Bit),
                 new SqlParameter ("@illegal",SqlDbType.Bit),
                };
                paras[0].Value = username;
                paras[1].Value = ip;
                paras[2].Value = time;
                paras[3].Value = logstate;
                paras[4].Value = illegal;
                string sqlcmd = "insert into User_Log (用户名,ip,登陆时间,在线状态,非法登陆) values (@username,@ip,@time,@logstate,@illegal)" ;
                
                SqlCommand cmd = new SqlCommand(sqlcmd, conn);
                
               cmd.Parameters.AddRange(paras);