Reputation: 3437
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
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