Puja Surya
Puja Surya

Reputation: 1297

how to add auto increment and primary key in c#

how to add auto increment and primary key using c# ?

im use sql server 2008 and sqlite

here is my code

use 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);

use sql server

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);

EDIT

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);
        }

Upvotes: 0

Views: 832

Answers (2)

Edper
Edper

Reputation: 9322

In sql server the keyword is PRIMARY KEY and IDENTITY and for sql lite it is PRIMARY KEY AUTOINCREMENT.

Upvotes: 0

David -
David -

Reputation: 2031

For SQL Server check this http://www.w3schools.com/sql/sql_autoincrement.asp and for SQLite, this http://www.tutorialspoint.com/sqlite/sqlite_using_autoincrement.htm

So, i think your code must look like this

for 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);

and this for 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);

Upvotes: 1

Related Questions