-1

我想从 C# 执行一条 SQL 命令

我有:

ccDc = getDataContext();
int MD5 = ccDc.ExecuteCommand("SELECT HASHBYTES('MD5', ChunkData) FROM dbo.x where id={0}", Id);

当我运行这个

SELECT HASHBYTES('MD5', ChunkData) FROM dbo.x where Id = '40'

我可以看到 md5 的字符串,但在 c# 中它只返回一个整数。但我需要将结果保存在字符串中。

我该怎么做?

4

2 回答 2

0

The below assumes that getDataContext() is what creates the SQL connection.

ccDc = getDataContext();

using (SqlCommand command = new SqlCommand(
    string.Format("SELECT HASHBYTES('MD5', ChunkData) FROM dbo.x where id={0}", Id),
    ccDc))
{
    using (SqlDataReader reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            for (int i = 0; i < reader.FieldCount; i++)
            {
                Console.WriteLine(reader.GetValue(i)); // or do whatever you want with the results...
            }
        }
    }
}

You should parameterize your query to prevent SQL injection, but there are plenty of tutorials and questions on that.

于 2015-10-09T13:09:37.567 回答
-1
SqlCommand command = new SqlCommand(string.Format("SELECT HASHBYTES('MD5', ChunkData) FROM dbo.x where id={0}", Id), connection);
string md5 = (string)command.ExecuteScalar();
于 2015-10-09T13:12:29.307 回答