从数据库获取值并添加到变量 [英] getting a value from database and adding to a variable

查看:57
本文介绍了从数据库获取值并添加到变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从数据库中获取值,并使用相应的数据填充变量和数组.尽管在使用getint32之类的东西时遇到了麻烦.任何帮助将不胜感激!我尝试使用

I'm trying to take values from my database and fill variables and an array with the corresponding data. Having trouble though when using getint32 and stuff like that. Any assistance would be greatly appreciated! I've attempted to use the numbers of the column to pull that information but when I do it doesn't work.

推荐答案

一个基本示例,搜索具有特定名字的项目,然后收集数据.如果我们期望一条记录,那么逻辑将失去while循环.

A basic example to search for items with a specific first name then collect the data. If we expect one record the logic loses the while loop.

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var myDataList = new List<SomeClass>();
            string firstName = "Karen";
            using (SqlConnection cn = new SqlConnection() { ConnectionString = "TODO" })
            {
                using (SqlCommand cmd = new SqlCommand() { CommandText = "SELECT id, LastName FROM Customers WHERE FirstName = @FirstName", Connection = cn })
                {
                    cmd.Parameters.AddWithValue("@FirstName", firstName);
                    cn.Open();
                    SqlDataReader reader = cmd.ExecuteReader();
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            myDataList.Add(new SomeClass() { id = reader.GetInt32(0), LastName = reader.GetString(1) });
                        }
                    }
                    reader.Close();
                }
            }
        }
    }
    public class SomeClass
    {
        public int id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

如果使用MS-Access而不是Sql-Server,则将Sqlxxx替换为OleDb对象.

If using MS-Access instead of Sql-Server then replace Sqlxxx with OleDb objects.


这篇关于从数据库获取值并添加到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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