将数据库绑定到对象 [英] Bind Database to Objects

查看:114
本文介绍了将数据库绑定到对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这是否是正确的术语,但我想知道是否可以绑定从数据库到对象的一行(数据)。我正在开展一个学校项目,我们决定创建这个应用程序来跟踪用户的BMI / BMR,并将其与他们输入的卡路里量进行比较。程序不会太深,所以它不会存储在数据库中消耗的卡路里。

I don't know if this is even the correct terminology but I was wondering if it is possible to bind a row (of data) from a database to an object. I am working on a school project and we have decided to create this application to track a user's BMI/BMR and compare it to the amount of calories they have input. The program doesn't go too in depth so it does not store the calories consumed in the database.

所以这里是我的问题。我的数据库中有一行:

So here is my problem. I have a row in my database:

First_Name - Last_Name - Height_Inches - Weight_Pounds

First_Name -- Last_Name -- Height_Inches -- Weight_Pounds

我想我想要我的程序要做的是,如果我有一个对象的属性FirstName,LastName,HeightInches,WeightPounds,是以某种方式查询数据库的一行,并将值放入对象。到目前为止,我们所学到的都是将数据绑定到控件,这在我的情况下并不真正有用,因为工作将在幕后完成。

And I guess what I am thinking I want my program to do is if I have an object with properties for FirstName, LastName, HeightInches, WeightPounds, is to somehow query the database for one row and put the values into the object. All we have learned so far is binding the data with controls which doesn't really help in my case since the work is going to be done behind the scenes.

这是模糊的。

推荐答案

我不知道VB.Net的语法非常好,所以这里有一些C#可能会有帮助:)应该很容易翻译。还有,自从我做了原始的ADO.Net,因此它可能不是完全准确的一段时间。

I don't know VB.Net's syntax very well, so here's some C# that might help :) Should be easy enough to translate. Also, it's been awhile since I've done raw ADO.Net so it might not be entirely accurate.

        using (SqlConnection conn = new SqlConnection("ConnectionStringGoesHere"))
        {
            string query = @"select First_Name, Last_Name, Height_Inches, Weight_Pounds from table_name";

            SqlCommand cmd = new SqlCommand(query, conn);
            conn.Open();
            IDataReader reader = cmd.ExecuteReader();

            BMIObject bmi = new BMIObject();
            bmi.FirstName = (string)reader["First_Name"];
            bmi.LastName = (string)reader["Last_Name"];
            bmi.Weight = (int)reader["Weight_Pounds"];
            bmi.Height = (int)reader["Height_Inches"];

            reader.Close();

            return bmi;
        }

这篇关于将数据库绑定到对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆