简体   繁体   English

如何使用ADO.NET在C#中从SQL Server检索数据?

[英]How to retrieve data from SQL Server in C# using ADO.NET?

Would you please show me how to retrieve data from SQL Server to C# (Windows Forms application)? 您能否告诉我如何将数据从SQL Server检索到C#(Windows窗体应用程序)?

Consider I have a textbox and I need to fill it with data from SQL Server WHERE 'emp_id = something' for example, how can I do it without a DataGridView? 考虑到我有一个文本框,我需要用SQL Server WHERE 'emp_id = something'数据填充它,如何在没有DataGridView的情况下做到这一点?

Or take this another example: 或举另一个例子:

SELECT sum(column) FROM table_name

How to get the value of the above command (also without a DataGridView)? 如何获取上述命令的值(也没有DataGridView)?

Filling a Textbox: 填充文本框:

using (var sqlConnection = new SqlConnection("your_connectionstring"))
{
    sqlConnection.Open();

    using (var sqlCommand = sqlConnection.CreateCommand())
    {
        sqlCommand.CommandText = "select sum(field) from your_table";

        object result = sqlCommand.ExecuteScalar();

        textBox1.Text = result == null ? "0" : result.ToString();
    }

    sqlConnection.Close();

}

for reading more than one row you can take a look at SqlCommand.ExecuteReader() 要读取多个行,可以查看SqlCommand.ExecuteReader()

There are multiple ways to achieve this. 有多种方法可以实现此目的。 You can use DataReader or DataSet \\ DataTable . 您可以使用DataReaderDataSet \\ DataTable These are connected and disconnected architectures respectively. 它们分别是连接和断开的体系结构。 You can also use ExecuteScalar if you want to retrieve just one value. 如果只想检索一个值,也可以使用ExecuteScalar

Recommendations: 建议:

  • Enclose SqlConnection (and any other IDisposable object) in using block. SqlConnection (和任何其他IDisposable对象)包含在using块中。 My code uses try-catch block. 我的代码使用try-catch块。
  • Always use parameterized queries. 始终使用参数化查询。

Following is some example code with DataReader in case your query returns multiple rows. 以下是DataReader一些示例代码,以防查询返回多行。 The code is copied from here . 代码从这里复制。

//Declare the SqlDataReader
SqlDataReader rdr = null;

//Create connection
SqlConnection conn = new SqlConnection("Your connection string");

//Create command
SqlCommand cmd = new SqlCommand("Your sql statement", conn);

try
{
    //Open the connection
    conn.Open();

    // 1. get an instance of the SqlDataReader
    rdr = cmd.ExecuteReader();

    while(rdr.Read())
    {
        // get the results of each column
        string field1 = (string)rdr["YourField1"];
        string field2 = (string)rdr["YourField2"];
    }
}
finally
{
    // 3. close the reader
    if(rdr != null)
    {
        rdr.Close();
    }

    // close the connection
    if(conn != null)
    {
        conn.Close();
    }
}

In case your query returns single value, you can continue with above code except SqlDataReader . 如果您的查询返回单个值,则可以继续使用上述代码( SqlDataReader除外)。 Use int count = cmd.ExecuteScalar(); 使用int count = cmd.ExecuteScalar(); . Please note that ExecuteScalar may return null ; 请注意, ExecuteScalar可能返回null so you should take additional precautions. 因此,您应该采取其他预防措施。

You need to use direct database access such as in the System.Data.SqlClient Namespace which is documented here System.Data.SqlClient Namespace . 您需要使用直接数据库访问权限,例如在System.Data.SqlClient命名空间中记录的System.Data.SqlClient命名空间

Basically, look up creating a SQLConnection and SQLCommand and using them to retrieve the data. 基本上,查找创建SQLConnection和SQLCommand并使用它们来检索数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM