comm.Parameters.Add()添加参数到参数集 String to int

/// <summary>
    /// 添加日志
    /// </summary>
    /// <param name="LogContent"></param>
    /// <param name="AdminID"></param>
    /// <param name="Dept"></param>
    public void add_log(string LogContent, string AdminID, string Dept)
    {
        SqlConnection conn = new SqlConnection(getConnStr());
        string sqlstr = "insert into Log(LogTime,LogContent,AdminID,Dept)values(@LogTime,@LogContent,@AdminID,@Dept)";
        SqlCommand comm = new SqlCommand(sqlstr, conn);
        comm.Parameters.Add("@LogTime", SqlDbType.VarChar);
        comm.Parameters.Add("@LogContent", SqlDbType.VarChar);
        comm.Parameters.Add("@AdminID", SqlDbType.VarChar);
        comm.Parameters.Add("@Dept", SqlDbType.VarChar);
        comm.Parameters["@LogTime"].Value = System.DateTime.Now.ToString();
        comm.Parameters["@LogContent"].Value = LogContent;
        comm.Parameters["@AdminID"].Value = AdminID;
        comm.Parameters["@Dept"].Value = Dept;
        conn.Open();
        comm.ExecuteNonQuery();
        conn.Close();
        conn.Dispose();
    }

comm.Parameters.Add()添加参数到参数集,add里面的第一个参数是要添加的参数名,第二个参数是参数的数据类型
Parameters的作用就是把存储过程执行结束后得到的参数传到程序里

 

 

 

首先,我要指出的是,在 C# 中,int 其实就是 System.Int32,即都是32位的。

其次,(int) 和 Convert.ToInt32 是两个不同的概念,前者是类型转换,而后者则是内容转换,它们并不总是等效的。我们很清楚 C# 提供类型检查,你不能把一个 string 强制转换成 int,隐式转换就更加不可能,例如如下的代码就行不通了:

string text = "1412";
int id = (int)text;

因为 string 和 int 是两个完全不同并且互不兼容的类型。说到这里,你可能会问什么才算是兼容的呢?其实,能够使用 (int) 进行强类型转换的只能是数值类型了,例如 long、short、double等,不过进行这种转换时你需要考虑精度问题。

然而,我们很清楚上面的代码中 text 实际上储存的是一个数值,我们希望把这个数值提取出来并以 int 的形式储存起来以便日后的运算使用,那么你就需要进行内容转换了。内容转换也叫内容解释,我们把上面的代码稍稍修改就可以达到目的了:

string text = "1412";
int id = Convert.ToInt32(text);

除此之外,你还可以使用 Int32.Parse 和 Int32.TryParse 来进行解释。

另外,你发现 Convert.ToInt32 有很多重载版本,例如 Convert.ToInt32(double value);,当我们用这个版本来把一个 double 转换成 int 时,ToInt32 会检查被转换的数值是否能够用 int 表示,即是否会发生“越界”,如果是就会抛出 OverflowException,否则就会为你转换,但使用 (int) 进行强制转换,如果被转换的数值大于 Int32.MaxValue,那么你将得到一个错误的结果,例如下面的代码:

double d = Int32.MaxValue + 0.1412;
int i = (int)d;

不过无论你进行什么数值转换,精度问题都是必须考虑的。

如果转换成16位的整数可以用: Convert.ToInt16();

 

例子:

using System;
class ChangeTime
{
public static void Main(){
      Console.WriteLine("pls set your time:");
      string hour=Console.ReadLine(); //readline的函数是string类.
      int bb=Convert.ToInt16(hour); // 将string类转成int类.
      if (bb>24 || bb<0){
      Console.WriteLine("input wrong");
      return; //推出程序.
}
      if (bb%12!=bb){
      bb-=12;
             
      }
     
      Console.WriteLine("the change time:{0}",bb);

}
}

 

posted @ 2010-03-23 12:55  PROS  阅读(1917)  评论(0)    收藏  举报