如何使用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 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);
修改
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);
}
答案 0 :(得分:1)
对于SQL Server,请检查此http://www.w3schools.com/sql/sql_autoincrement.asp,对于SQLite,请检查此http://www.tutorialspoint.com/sqlite/sqlite_using_autoincrement.htm
所以,我认为你的代码必须看起来像这样
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);
这适用于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);
答案 1 :(得分:0)
在sql server中,关键字是PRIMARY KEY和IDENTITY,对于sql lite,它是PRIMARY KEY AUTOINCREMENT。