简体   繁体   English

如何计算条件下设置的记录数?

[英]How to count number of records set under a condition?

I'm basically new in coding, and I'm in uni, we have a small project to complete and I'm using OleDb to do it, as I have used it before, I'm trying to count the number of rows where a field is equal to a specific value, but I always get 0. To be more clear, I want statistics showing percentage of males/females who completed the survey(the program I'm making), currently I have 1 male and 2 females, so my string for all rows shows 3, which is correct, but when I want to count all the rows that contain females, it shows 0, so the total percentage is 0, and the textbox that's supposed to show the stat shows 0, here is the code:我基本上是编码新手,我在大学,我们有一个小项目要完成,我正在使用 OleDb 来完成它,因为我以前使用过它,我正在尝试计算行数一个字段等于一个特定的值,但我总是得到 0。为了更清楚,我想要统计显示完成调查的男性/女性的百分比(我正在制作的程序),目前我有 1 个男性和 2 个女性,所以我所有行的字符串显示 3,这是正确的,但是当我想计算包含女性的所有行时,它显示 0,所以总百分比为 0,并且应该显示统计信息的文本框显示为 0,这是代码:

private void Form2_Load(object sender, EventArgs e)
    {
        String connectionString;
        connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\kubas\Desktop\MyProject\ProjectDB.accdb'";
        using (OleDbConnection myConnection = new OleDbConnection(connectionString))
        {
            string Gender1 = "Female";
            OleDbConnection con;
            OleDbCommand cmd = new OleDbCommand();
            OleDbCommand cmd1 = new OleDbCommand();
            con = new OleDbConnection(connectionString);
            con.Open();
            cmd.CommandText = "SELECT Count(Gender) FROM Survey WHERE Gender = '" + Gender1 + "'";
            cmd1.CommandText = "SELECT Count(Gender) FROM Survey";
            cmd.Connection = con;
            cmd1.Connection = con;
            con.Close();
            try
            {
                con.Open();
                int total = (Int32)cmd.ExecuteScalar();
                int total1 = (Int32)cmd1.ExecuteScalar();
                int tot;
                tot = total / total1 * 100;
                string ttal = Convert.ToString(tot);
                textBox1.Text = ttal;
                con.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }

            }

sorry if there is something you can't understand, English isn't my first language.抱歉,如果您有什么不明白的地方,英语不是我的第一语言。

Maybe try this command query: "SELECT Count(Gender) FROM Survey WHERE Gender = \\"" + Gender1 + "\\"";也许试试这个命令查询: "SELECT Count(Gender) FROM Survey WHERE Gender = \\"" + Gender1 + "\\"";

From what I can remember.据我所知。 access uses quotation marks for strings. access 对字符串使用引号。

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

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