0

如何使用 c# 添加自动增量和主键?

我使用 sql server 2008 和 sqlite

这是我的代码

使用 sqlite

Dictionary<String, String> field = new Dictionary<string, string>();
            field.Add("id", "INT");
            field.Add("mac", "VARCHAR(25)");
            field.Add("serial_number", "VARCHAR(25)");
            cDatabaseSQLite.CreateTables("satuan", field);

使用 sql 服务器

Dictionary<String, String> field = new Dictionary<string, string>();
            field.Add("id", "INT");
            field.Add("mac", "VARCHAR(25)");
            field.Add("serial_number", "VARCHAR(25)");
            cDatabaseSQLServer.CreateTables("satuan", field);

编辑

public int CreateTables(String tableName, Dictionary<String, String> data)
        {
            switch (sqlType)
            {
                case DATABASE_SQL_TYPE.DATABASE_SQL_TYPE_SQLITE:
                    return cSQLite.CreateTables(tableName, data);
                case DATABASE_SQL_TYPE.DATABASE_SQL_TYPE_MSSQL:
                    return cSQL.CreateTables(tableName, data);
            }
            return 0;
        }


public int CreateTables(String tableName, Dictionary<String, String> data)
        {
            string s = "CREATE TABLE " + tableName + " (";
            bool first = true;
            foreach (KeyValuePair<String, String> val in data)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    s = s + ",";
                }
                string s1;
                s1 = String.Format("{0} {1}", val.Key, val.Value);
                s = s + s1;
            }
            s = s + ")";
            return this.ExecuteNonQuery(s);
        }
4

2 回答 2

1

对于 SQL Server,请查看此http://www.w3schools.com/sql/sql_autoincrement.asp,对于 SQLite,请查看此http://www.tutorialspoint.com/sqlite/sqlite_using_autoincrement.htm

所以,我认为你的代码必须是这样的

对于 SQLite

Dictionary<String, String> field = new Dictionary<string, string>();
            field.Add("id", "INTEGER PRIMARY KEY AUTOINCREMENT");
            field.Add("mac", "VARCHAR(25)");
            field.Add("serial_number", "VARCHAR(25)");
            cDatabaseSQLite.CreateTables("satuan", field);

这适用于 SQL Server

Dictionary<String, String> field = new Dictionary<string, string>();
            field.Add("id", "INT PRIMARY KEY IDENTITY");
            field.Add("mac", "VARCHAR(25)");
            field.Add("serial_number", "VARCHAR(25)");
            cDatabaseSQLServer.CreateTables("satuan", field);
于 2013-06-26T07:08:10.197 回答
0

在 sql server 中,关键字是 PRIMARY KEY 和 IDENTITY,而对于 sql lite,它是 PRIMARY KEY AUTOINCREMENT。

于 2013-06-26T07:15:12.083 回答