从C#代码执行SQL查询

时间:2015-05-22 08:48:14

标签: c# sql-server visual-studio

我正在尝试从C#代码执行SQL查询,但它不返回任何值,但是当我直接向SQL编写查询时,它工作正常。

static int TestGettingData()
{
        int rows;
        string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using (SqlCommand command = new SqlCommand("SELECT [UserName] FROM [aspnet_Users]", connection))
            {
                connection.Open();
                rows = command.ExecuteNonQuery();
            }
        }
        return rows;
}

连接字符串:

<connectionStrings>
<add name ="DefaultConnection" connectionString="Server=myServer;
            Database=MyDatabase;User 
            Id=User;
            Password=password;
            MultipleActiveResultSets=True;"
            providerName="System.Data.SqlClient"/>
</connectionStrings>

TestGettingData()总是返回-1。

3 个答案:

答案 0 :(得分:4)

有多种方法可以从数据库中获取数据

<强>的ExecuteScalar

如果您有一个结果字段,则可以使用

string Command = "SELECT [UserName] FROM [aspnet_Users];";
using (SqlConnection myConnection = new SqlConnection(ConnectionString))
{
    myConnection.Open();
    using (SqlCommand myCommand = new SqlCommand(Command, myConnection))
    {
        string Result = (string)myCommand.ExecuteScalar(); // returns the first column of the first row
    }
}

SqlDataAdapter

如果您希望多行/列,可以通过

将其加载到DataTable中
string Command = "SELECT [UserName] FROM [aspnet_Users]";
using (SqlConnection myConnection = new SqlConnection(ConnectionString))
{
    using (SqlDataAdapter myDataAdapter = new SqlDataAdapter(Command, myConnection))
    {
        DataTable dtResult = new DataTable();
        myDataAdapter.Fill(dtResult);
    }
}

SqlDataReader

另一个解决方案是SQLDataReader。例如。如果要将列的所有行加载到List中。这比DataAdapter的开销要小。

List<string> Result = new List<string>();
string Command = "SELECT [UserName] FROM [aspnet_Users];";
using (SqlConnection mConnection = new SqlConnection(ConnectionString))
{
    mConnection.Open();
    using (SqlCommand cmd = new SqlCommand(Command, mConnection))
    {
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                Result.Add((string)reader[0]);
            }
        }
    }
}

答案 1 :(得分:2)

因为documentation这么说;

  

对于UPDATE,INSERT和DELETE语句,返回值为   受命令影响的行数。当a上存在触发器时   正在插入或更新的表,返回值包括数字   受插入或更新操作影响的行数和数字   受触发器或触发器影响的行数。 适用于所有其他类型的   语句,返回值为-1 。如果发生回滚,则返回   值也是-1。

您可以使用COUNT(*) ExecuteScalar方法获取您的电话号码。

using (SqlCommand command = new SqlCommand("SELECT COUNT([UserName]) FROM [aspnet_Users]", connection))
{
     connection.Open();
     rows = (int)command.ExecuteScalar();
}

答案 2 :(得分:0)

我认为这是从数据库访问和检索数据的最佳方式:

创建DBconnection类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SQLexample
{
/// <summary>
/// A class that makes the connection to the SQL Database
/// </summary>
class DBconnection
{
    // variables
    private string sql_string;
    private string strCon;
    System.Data.SqlClient.SqlDataAdapter da_1;

    // set methods
    public string Sql
    {
        set { sql_string = value; }
    }

    public string connection_string
    {
        set { strCon = value; }
    }

    // DataSet
    public System.Data.DataSet GetConnection
    {
        get { return MyDataSet(); }
    }

    // MyDataSet method
    private System.Data.DataSet MyDataSet()
    {
        System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strCon);
        con.Open();

        da_1 = new System.Data.SqlClient.SqlDataAdapter(sql_string, con);

        System.Data.DataSet dat_set = new System.Data.DataSet();
        da_1.Fill(dat_set, "Table_Data_1");

        con.Close();

        return dat_set;
    }

    // Update DB method
    public void UpdateDB(System.Data.DataSet ds)
    {
        System.Data.SqlClient.SqlCommandBuilder cb = new System.Data.SqlClient.SqlCommandBuilder(da_1);
        cb.DataAdapter.Update(ds.Tables[0]);
    }
}
}

然后,在您的其他课程中,无论何时您想要访问数据库,都可以这样做:

try
{
    objConnect = new DBconnection();
    conStringAUTH = Properties.Settings.Default.authConnectionString;

    objConnect.connection_string = conStringAUTH;
    objConnect.Sql = "QUERY GOES HERE";

    ds = objConnect.GetConnection;

    // Data manipulation
    maxRows = ds.Tables[0].Rows.Count;

    if (maxRows == 0)
    {
        // Your query returned no values
    }

}
catch (Exception err)
{
    MessageBox.Show(err.Message);
}

希望这会有所帮助......