update sql statement with unknown name/amount of params

后端 未结 3 1638
礼貌的吻别
礼貌的吻别 2021-01-16 07:12

I have a classic ASP site, that I am slowly upgrading. I would like to create a function to securely update a SQL database without specifying parameters man

3条回答
  •  爱一瞬间的悲伤
    2021-01-16 08:07

    you need to do something like this....needs more coding obviously....

     static void Main(string[] args)
        {
            var values = new Dictionary( );
    
            values.Add( "name", "timmerz" );
            values.Add( "dob", DateTime.Now );
            values.Add( "sex", "m" );
    
            SqlUpdate( "sometable", values );
        }
    
        public static void SqlUpdate( string table, Dictionary values, string where )
        {
            var equals      = new List( );
            var parameters  = new List( );
    
            var i = 0;
    
            foreach( var item in values )
            {
                var pn = "@sp" + i.ToString( );
    
                equals.Add( string.Format( "{0}={1}", item.Key, pn ) );
    
                parameters.Add( new SqlParameter( pn, item.Value ) );
    
                i++;
            }
    
            string command = string.Format( "update {0} set {1} where {2}", table, string.Join( ", ", equals.ToArray( ) ), where );
    
            var sqlcommand = new SqlCommand(command);
    
            sqlcommand.Parameters.AddRange(parameters.ToArray( ) );
    
            sqlcommand.ExecuteNonQuery( );
        }
    

提交回复
热议问题