C#操作数据库获取指定列数据类型为int的值

Technorati 标签: C#,数据库
private static void
使用原始SQL命令打印字段值() { SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=图库;Integrated Security=True"); try { conn.Open(); Console.WriteLine("Sucess"); } catch (Exception) { Console.WriteLine("打开失败"); } SqlCommand comm = conn.CreateCommand(); comm.CommandText = "select * from 会员数据"; SqlDataReader reader = comm.ExecuteReader(); while (reader.Read()) { Console.WriteLine("你要打印的数据:{0}", reader.GetSqlInt16(reader.GetOrdinal("年龄"))); } }

image

想使用上面数据库用程序来得到所有的年龄,结果老是出错,说是指定的转换无效,自己研究了下,原来数据库中的int字段在转换时需要使用int32,而不是int16

image

改成int32程序就正确运行了

Console.WriteLine("你要打印的数据:{0}", reader.GetSqlInt32(reader.GetOrdinal("年龄")));

image

posted @ 2011-04-13 23:00  爱玩的安哥  阅读(3522)  评论(0编辑  收藏  举报