我有一个访问数据库,我想在表中添加一行。但是我希望得到id(colum name - > id)。
这是我用来注册新组的代码:
int id;
internal static void agregarGrupo(int grado, char grupo, String escuela, int maestro)
{
try
{
comand.Connection = conection;
comand.CommandText =
"INSERT INTO Grupos " +
"(grado, grupo, escuela, maestro) " +
"VALUES(" + grado + ", '" + grupo + "' , '" + escuela + "', " + maestro + ")";
conection.Open();
id = comand.ExecuteScalar();
}
finally
{
conection.Close();
}
}
我做错了什么?
如何在不创建新查询的情况下获取新行的id?
答案 0 :(得分:0)
您必须再次进行查询以获取最后一个标识值,因为Access不支持批处理命令。您需要重用连接并发出另一个命令:
string query = "SELECT @@IDENTITY";
var cmd = new OleDbCommand(query, (OleDbConnection)command.Connection);
int newId = (int)cmd.ExecuteScalar();
或者您可以在这行代码之后执行此操作:
id = comand.ExecuteScalar(); // this is your code
command.CommandText = "SELECT @@IDENTITY";
int newId = (int)command.ExecuteScalar();