-2

好的,我有一个 SQL 查询,需要在单击按钮时运行,然后输出到数据集。

public partial class Form1 : Form
{
    private void Form1_Load(object sender, EventArgs e)
    {
        Assembly.GetExecutingAssembly().GetName().Version.ToString();
        var line = txtLine.Text;
        var serial = txtSerial.Text;
        var station = txtStation.Text;
    }

    private void btnGo_Click(object sender, EventArgs e)
    {
        var line = txtLine.Text;
        var serial = txtSerial.Text;
        var station = txtStation.Text;

        if (txtLine.Text.Trim().Length == 0)
        {
            MessageBox.Show("Please enter a Line");
        }
        else if (txtSerial.Text.Trim().Length == 0)
        {
            MessageBox.Show("Please enter a Serial");
        }
        else if (txtStation.Text.Trim().Length == 0)
        {
            MessageBox.Show("Please enter a Station");
        }
        else
        {
            //SQL command goes here.
        }
    }
}

我有 SQL 命令,我只需要知道如何将其作为非存储过程执行并将数据输出到 dataGridView1 对象。

4

1 回答 1

0

您没有提供足够的信息来向您展示伪代码。但是,使用该using 语句来确保所有实现IDisposable都得到正确处理并且连接被关闭(即使发生错误)。

使用 sql-parameters 来避免 sql 注入和转换/本地化问题。

string sql = "SELECT Columns FROM dbo.TableName WHERE Column=@ParamName";
using (var con = new SqlConnection("Connection String Here"))
using (var da = new SqlDataAdapter(sql, con))
{
    da.SelectCommand.Parameters.AddWithValue("@ParamName", "Param Value");
    // other parameters
    DataTable table = new DataTable();
    da.Fill(table);
    dataGridView1.DataSource = table;             
}
于 2013-08-07T22:07:16.557 回答