用Csharp 写一个 查询SQL SERVER 查询表字段
时间: 2024-05-09 14:20:49 浏览: 156
以下是用 C# 查询 SQL Server 数据库中表字段的示例代码:
```
using System;
using System.Data.SqlClient;
namespace QueryTableFields
{
class Program
{
static void Main(string[] args)
{
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword";
string tableName = "myTable";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand($"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='{tableName}'", connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetString(0));
}
reader.Close();
}
}
}
}
```
在这个示例中,我们使用 `SqlConnection` 类连接到 SQL Server 数据库。然后,我们使用 `SqlCommand` 类执行一个 SQL 查询语句,查询表 `myTable` 中的所有字段名。最后,我们使用 `SqlDataReader` 类读取查询结果,并将每个字段名打印到控制台上。
请注意,为了安全起见,我们使用参数化查询语句来避免 SQL 注入攻击。在实际应用中,您应该使用实际的参数值来替换查询语句中的参数。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)