0

我正在尝试将文本框中的值传递到 sql 查询中,以查找输入的数字出现在数据库中的次数。我是 C# 编程的新手,任何帮助都会非常感激:)

我的 SQL 查询是标量的,如下所示:

SELECT COUNT(WinNo01) AS CountOfball1
FROM tblLotto
GROUP BY WinNo01
HAVING WinNo01 = @num

我的代码是这样的:

namespace Assessment2
{
    public partial class Statistics : Form
    {
        public Statistics()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int amount = 0;
            amount = int.Parse(textBox1.Text);            

            label2.Text = "1st position appearances : " + tblLottoTableAdapter.StatisticRow01(amount).ToString();                             
        }
    }
}

注意:我可以通过取出@num 并输入一个值来使查询工作,但我需要它从文本框中读取值。我很绿所以请给我简单的答案:)

4

2 回答 2

1

MSDN上的这篇文章可能对你有帮助:

将 TextBox 值存储在 C# 中的 SQL 表中

因此,考虑到上述情况,您可以这样做:

string query = "INSERT INTO MyTable VALUES (@MyValue)";
SqlCommand cmd = new Sqlcommand(query, sqlConn);
cmd.Parameters.Add("@MyValue", SqlDbType.Varcharm, 50).Value = myTextBox.Text;
cmd.Connection.Open();
try
{
   cmd.ExecuteNonQuery();
}
于 2013-10-22T20:51:27.807 回答
0
private void button1_Click(object sender, EventArgs e)
{
    int amount;
    if(int.TryParse(textBox1.Text,out amount))
    {
        using (var com = new System.Data.SqlClient.SqlConnection("your connection string").CreateCommand())
        {
            com.CommandText = @"SELECT COUNT(WinNo01) AS CountOfball1
                            FROM tblLotto
                            GROUP BY WinNo01
                            HAVING WinNo01 = @num";
            com.Parameters.Add(new System.Data.SqlClient.SqlParameter("num", amount));
            com.Connection.Open();
            try
            {
                int result = Convert.ToInt32(com.ExecuteScalar());
                label2.Text = result.ToString();
            }
            finally 
            {
                com.Connection.Close();
            }
        }
    }
}
于 2013-10-22T21:24:17.947 回答