如何将 SQL 结果放入 STRING 变量中? [英] How can I get SQL result into a STRING variable?

查看:51
本文介绍了如何将 SQL 结果放入 STRING 变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 C# 字符串变量或字符串数​​组中获取 SQL 结果.是否可以?我需要以某种方式使用 SqlDataReader 吗?我对 C# 函数和所有函数都很陌生,曾经在 PHP 中工作,所以如果可以,请提供一个工作示例(如果相关,我已经可以连接和访问数据库,插入和选择..我只是不知道如何将结果存储在字符串变量中).

I'm trying to get the SQL result in a C# string variable or string array. Is it possible? Do I need to use SqlDataReader in some way? I'm very new to C# functions and all, used to work in PHP, so please give a working example if you can (If relevant I can already connect and access the database, insert and select.. I just don't know how to store the result in a string variable).

推荐答案

这不是历史上最好的例子,好像你不从数据库中返回任何行一样,你最终会遇到一个异常,但是如果您想使用数据库中的存储过程,而不是直接从您的代码中运行 SELECT 语句,那么这将允许您返回一个字符串:

This isn't the single greatest example in history, as if you don't return any rows from the database you'll end up with an exception, but if you want to use a stored procedure from the database, rather than running a SELECT statement straight from your code, then this will allow you to return a string:

public string StringFromDatabase()
    {
        SqlConnection connection = null;

        try
        {
            var dataSet = new DataSet();

            connection = new SqlConnection("Your Connection String Goes Here");
            connection.Open();

            var command = new SqlCommand("Your Stored Procedure Name Goes Here", connection)
            {
                CommandType = CommandType.StoredProcedure
            };

            var dataAdapter = new SqlDataAdapter { SelectCommand = command };

            dataAdapter.Fill(dataSet);

            return dataSet.Tables[0].Rows[0]["Item"].ToString();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message, ex);
        }
        finally
        {
            if (connection != null)
            {
                connection.Close();
            }
        }
    }

它肯定可以改进,但如果您想走存储过程路线,它会给您一个工作起点.

It can definitely be improved, but it would give you a starting point to work from if you want to go down a stored procedure route.

这篇关于如何将 SQL 结果放入 STRING 变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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