下面是我如何创建一个带有autoNumber字段的表:
ADOX.Catalog cat = new ADOX.Catalog();
ADOX.Table table = new ADOX.Table();
ADOX.Key tableKey = new Key();
ADOX.Column col = new Column();
String SecurityDBConnection = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}\\{1};", value, SecurityDBName);
// Define column with AutoIncrement features
col.Name = "ID";
col.Type = ADOX.DataTypeEnum.adInteger;
// Define security table
table.Name = "Security";
table.Columns.Append(col); // default data type is text[255]
table.Columns.Append("Username", ADOX.DataTypeEnum.adVarWChar, 255);
table.Columns.Append("Password", ADOX.DataTypeEnum.adVarWChar, 255);
table.Columns.Append("Engineer", ADOX.DataTypeEnum.adBoolean);
table.Columns.Append("Default", ADOX.DataTypeEnum.adBoolean);
tableKey.Name = "Primary Key";
tableKey.Columns.Append("ID");
tableKey.Type = KeyTypeEnum.adKeyPrimary;
// Add security table to database
cat.Create(SecurityDBConnection);
// Must create database file before applying autonumber to column
col.ParentCatalog = cat;
col.Properties["AutoIncrement"].Value = true;
cat.Tables.Append(table);
// Now, try to connect to cfg file to verify that it was created successfully
ADODB.Connection con = cat.ActiveConnection as ADODB.Connection;
if (con != null) con.Close();
下面是使用自动编号字段向表中插入记录的代码。请注意,插入语句中未指定 autoNumber 字段,并且字段名称用括号括起来。
public void WriteRecord(String sUsername, String sPassword, Boolean boEngineerRole, Boolean boDefaultUser)
{
String InsertQry = "Insert into Security([Username], [Password], [Engineer], [Default]) "
+ "values(@UserName, @Password, @Engineer, @Default)";
using (OleDbConnection connection = new OleDbConnection(SecurityDBConnection))
{
using (OleDbCommand command = new OleDbCommand(InsertQry, connection))
{
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("@UserName", sUsername);
command.Parameters.AddWithValue("@Password", sPassword);
command.Parameters.AddWithValue("@Engineer", boEngineerRole);
command.Parameters.AddWithValue("@DefaultUser", boDefaultUser);
connection.Open();
command.ExecuteNonQuery();
}
}
}