我有一个Windows窗体,它有以下文本框,并显示在网格视图中。应用程序使用C#连接到Access数据库。
Companyid (自动编号)
CompanyName(短讯)
TypeofCompany(短讯)
如何生成AutoNumber字段以使用INSERT语句更新自身?
例如,C001,C002,C003,C004……
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Shrenik_Salguna\Desktop\final.accdb;
Persist Security Info=False;");
con.Open();
OleDbCommand cmd = new OleDbCommand(@"INSERT INTO info
([Name of Company], [Type of Company]) VALUES('"+textBox1.Text+"','" + textBox2.Text + ")", con);
cmd.ExecuteNonQuery();
con.Close();发布于 2013-06-20 11:05:03
如果Companyid是Access表中的AutoNumber字段,则在INSERT语句中不包含该字段,因为Access数据库引擎负责处理该字段。
可以想象,您可以创建自己的包含"C001“、"C002”等的“自动增量”字段,但是如果您已经有了一个真正的AutoNumber字段,那么为什么还要麻烦呢?对于表中的每一行,您已经有了一个唯一的列,如果您想派生一个像"Cnnn“这样的标识符,那么您可以很容易地在C#中使用与这个VBA表达式等价的内容:
"C" & Format([Companyid], "000")发布于 2013-09-23 18:35:04
下面是我如何创建一个带有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字段向表中插入记录的代码。注意,autoNumber字段是而不是insert语句中指定的,字段名放在括号内。
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();
}
}
}https://stackoverflow.com/questions/17209905
复制相似问题