-1

我想检查我的表(在 sql 数据库中)是否为空,如果是,我可以放置一个按钮,允许用户创建他们的第一个......以及用户,以便他们可以使用该程序。

那么我如何检查用户没有帐户然后我如何添加一个新用户记住ID是一个主键并且设置为每个用户增加一个,在添加帐户时我是否需要包括一些方法?

摘要 = 我如何在表格中添加一些内容 + 添加时是否需要包含 ID,或者我是否需要忽略它,只添加用户名和密码之类的内容。

其次,我如何确定表是否为空

<<<<<我现在理解的基本思想只是这个错误是一个问题>>>>>

   System.Data.SqlClient.SqlCommand CheckNone = new System.Data.SqlClient.SqlCommand(
            "SELECT COUNT(*) from Users",
            con);
            con.Open();

            System.Data.SqlClient.SqlDataReader Checkreader = CheckNone.ExecuteReader();
            if (Checkreader.Read())
            {
                if (0 != Checkreader.GetInt16(Checkreader.GetOrdinal("COUNT(*)")))
                {

它会导致错误......像这样,indexoutofRangeException: COUNT( ) 等等我认为是因为这条线是错误的 if (0 != Checkreader.GetInt16(Checkreader.GetOrdinal("COUNT( )")))

特别是我尝试过的名称 COUNT(*)

4

4 回答 4

3

I would go with:

System.Data.SqlClient.SqlCommand CheckNone = new System.Data.SqlClient.SqlCommand(
        "IF EXISTS(SELECT * from Users) SELECT 1 ELSE SELECT 0",
        con);
        con.Open();

        var result = (int)CheckNone.ExecuteScalar();
        if (result==0)
        {
            //No users

This has the advantage (over using COUNT(*)) that, once the table is populated, you're not asking the server to count all of the rows when all you care about is whether rows exist or not (i.e. it more clearly states the fact you want to determine).

It also has the advantage that we don't open and then have to clean up a reader when all we care about is the first column of the first row of the result set - that's what ExecuteScalar is built for.

于 2013-05-24T06:52:41.120 回答
2

其次,我如何确定表是否为空

更改SELECT COUNT(*)SELECT COUNT(*) AS CountOfRecordsthenExecuteReader或仅保留语句原样和ExecuteScalar

于 2013-05-24T03:19:40.653 回答
0

尝试这个

con.Open();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * from Users",con);

DataTable table = new DataTable();

adapter.Fill(table);

if(table.Rows.Count == 0)
{
    //table is empty.
}

SqlDataAdapter示例

于 2013-05-28T06:08:43.003 回答
-1

我会在代码中尝试读取用户表。像这样的东西

注意:这是伪代码:

If not isdbnull(dataobject("nameoffield")
'''Do certain code
'''Show Button
ELSE
'''The user has an ID
'''Dont show button
END IF

就身份而言,您将身份列添加到表中,它会自动生成。在表中,您需要像这样创建它:

列名 INT Identity(seed,increment)

于 2013-05-24T02:51:10.507 回答