Q-bertsuit
Q-bertsuit

Reputation: 3437

Retrieving the primary key from a database

Is it possible to return the last primary key given in a database?

This is partly how I'm connecting to and adding stuff to my database, but if you need more infor please ask.

public partial class MainWindow : Window
{

System.Data.SqlClient.SqlConnection con;
System.Data.SqlClient.SqlDataAdapter da;

DataSet sessions;

Main

public MainWindow()
{
    InitializeComponent();
}

private void button1_Click(object sender, RoutedEventArgs e)
{
    con = new System.Data.SqlClient.SqlConnection();

    sessions = new DataSet();

    con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\md\\PokerDataBase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";

    con.Open();

    string sql = "SELECT * From Sessions";
    da = new System.Data.SqlClient.SqlDataAdapter(sql, con);
    da.Fill(sessions, "Sessions");

    con.Close();

    System.Data.SqlClient.SqlCommandBuilder cb;
    cb = new System.Data.SqlClient.SqlCommandBuilder(da);

    DataTable dt = sessions.Tables["Sessions"];


    DataRow table = sessions.Tables["Sessions"].Rows[position];
    table[0] = "Some Data";
    table[1] = "Some Data";
    table[2] = "Some Data";
    table[3] = 2;
    table[4] = 3;
    sessions.Tables["Sessions"].Rows[2].Delete();
    sessions.Tables["Sessions"].Rows.InsertAt(table, 2);

    da.Update(sessions, "Sessions");
}
}

Thanks for having a look!

Upvotes: 4

Views: 1276

Answers (2)

Lajos Arpad
Lajos Arpad

Reputation: 76436

If you want to get the last primary key from a table and you have it increments automatically on every insert, then you can just ask for its maximal value. If you want from the database, then you can use scope identity.

Upvotes: 0

Yaroslav
Yaroslav

Reputation: 6534

I guess you are asking for the last inserted primary key value? Then SCOPE_IDENTY is your friend. Take a look here and MSDN for detailed information

Upvotes: 4

Related Questions