从 SQL Server 数据库获取数据 [英] Getting data from SQL Server database

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

问题描述

寻找从数据库中获取单个值的最简单方法.当您考虑在 .NET 语言中存在的所有 9,000 种方法时,这会让人感到困惑.SqlCommands、DataReaders、Recordsets...天​​哪!

Looking for the simplest way to get a single value from a database. This gets confusing when you consider all of the 9,000 ways that exist to do this in a .NET language. SqlCommands, DataReaders, Recordsets... oh my!

假设我已经打开了与数据库的连接.我只是想做这样的事情:

Assume I already have a connection to the DB opened. I simply want to do something like this:

Dim age As Integer = <SQL statement here>

推荐答案

SqlConnection conn = new SqlConnection("connection string goes here");
SqlCommand cmd = new SqlCommand("SELECT foo FROM ...", conn);

conn.Open();
int age = (int)cmd.ExecuteScalar();
conn.Close();

不是 VB.Net 的人,但我认为它在 VB.Net 中看起来像这样:

Not a VB.Net guy, but I think it would look something like this in VB.Net:

Dim conn As SqlConnection = new SqlConnection("connection string goes here")
Dim cmd As SqlCommand = new SqlCommand("SELECT foo FROM ...", conn);

conn.Open()
Dim age As Integer = Convert.ToInt32(cmd.ExecuteScalar())
conn.Close()

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

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