检索列数在SQL表 - C# [英] Retrieve number of columns in SQL Table - C#
本文介绍了检索列数在SQL表 - C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很新的C#。我想要检索的列使用数字:
SELECT COUNT(*)FROM SYS.COLUMNS
能否请你解释如何使用该命令,并把它变成一个变量。
解决方案
字符串的connectionString =
数据源=(本地);初始目录=罗斯文;
+集成安全性=真;
//提供一个参数占位符查询字符串。
字符串查询字符串=
选择从SYS.COLUMNS COUNT(*);
//指定参数值。
INT paramValue = 5;
//创建并打开一个使用块的连接。本
//确保所有资源将被关闭和处置
//当code退出。
使用(SqlConnection的连接=
新的SqlConnection(的connectionString))
{
//创建命令和参数对象。
SqlCommand的命令=新的SqlCommand(查询字符串,连接);
//打开在一个try / catch块的连接。
//创建并执行DataReader的,结果写
//设置控制台窗口。
尝试
{
connection.Open();
SqlDataReader的读卡器= Command.ExecuteReader却();
而(reader.Read())
{
Console.WriteLine(\ t {0},
读者[0]);
}
reader.Close();
}
赶上(例外前)
{
Console.WriteLine(ex.Message);
}
到Console.ReadLine();
}
I'm very new to C#. I'm trying to retrieve the number of columns using:
SELECT count(*) FROM sys.columns
Could you please explain how to use the command and put it into a variable.
解决方案
string connectionString =
"Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=true";
// Provide the query string with a parameter placeholder.
string queryString =
"SELECT Count(*) from sys.columns";
// Specify the parameter value.
int paramValue = 5;
// Create and open the connection in a using block. This
// ensures that all resources will be closed and disposed
// when the code exits.
using (SqlConnection connection =
new SqlConnection(connectionString))
{
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(queryString, connection);
// Open the connection in a try/catch block.
// Create and execute the DataReader, writing the result
// set to the console window.
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("\t{0}",
reader[0]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
这篇关于检索列数在SQL表 - C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文