.net Access 新增记录后获取自动编号的值
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsApplication2
{
public partial class Form1 : Form
{
OleDbConnection myConnection;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
myConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Logs.mdb;Persist Security Info=False");
string cmdText="insert into LogInfo (LeiBie) values('bbb')";
int sss=returnID(cmdText);
}
/// <summary>
///
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public int returnID(string sql)
{
int nID = 0;
try
{
myConnection.Open();
OleDbTransaction myTransaction = myConnection.BeginTransaction(IsolationLevel.ReadCommitted);
OleDbCommand myCommand = new OleDbCommand(sql, myConnection);
myTransaction.Commit();
myCommand.ExecuteNonQuery();
myCommand.CommandText = "select @@identity as id";
nID = Convert.ToInt32(myCommand.ExecuteScalar());
}
catch (Exception e)
{
throw new Exception(e.Message);
}
finally
{
myConnection.Close();
}
return nID;
}
}
}