以下是一个C#查询用户信息的示例代码:

using System;
using System.Data.SqlClient;

class Program
{
    static void Main(string[] args)
    {
        string connectionString = "Data Source=YOUR_SERVER_NAME;Initial Catalog=YOUR_DATABASE_NAME;Integrated Security=True";
        string query = "SELECT * FROM Users WHERE UserName=@UserName";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand(query, connection);
            command.Parameters.AddWithValue("@UserName", "john");

            try
            {
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();

                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        Console.WriteLine("{0}\t{1}\t{2}\t{3}", reader.GetInt32(0), reader.GetString(1), reader.GetString(2), reader.GetString(3));
                    }
                }
                else
                {
                    Console.WriteLine("No rows found.");
                }
                reader.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        Console.ReadKey();
    }
}

在上面的代码中,我们使用了SqlConnectionSqlCommand对象来连接数据库并执行查询语句。我们还使用了SqlDataReader对象来遍历查询结果。在查询中,我们使用了参数化查询来避免SQL注入攻击。在这个例子中,我们查询了一个名为“john”的用户,并打印了他的所有信息。

帮我写一个C# 查询用户信息的代码

原文地址: https://www.cveoy.top/t/topic/b2xV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录