winforms c#でクイズ アプリケーションを作成しています。質問と回答をフォーム ロードとしてフォームにロードします。フォームに「次へ」ボタンが 1 つあり、1 つの質問が完了したら、[次へ] ボタンを押して次の質問に進みます。今、私はそのユーザーのログインに基づいてそのユーザーのセッションを保存したいと考えています。ユーザーがログインすると、session
開始します。残念ながらForm Closed
、ユーザーが再度ログインすると、session
が開始されます。session
閉じている(古い状況を意味する)新しいものではありません...注:「Windowsを使用していますSQL SERVER 2008 R2
」..よろしくお願いします..
1 に答える
クイズ アプリケーションは、ユーザーが [次へ] ボタンをクリックしたときの音から、ユーザーの回答をデータベースに書き込みます。おそらく、回答は、ユーザー ID を参照するための列と、質問 ID とユーザーが回答した別の列を含むテーブルに記録されます。
この種のテーブル構造を使用している場合、ユーザーが最後に回答した質問を確認し、ユーザーが再度ログインしたときに次の質問を表示することはできませんか?
SELECT * FROM AnswersTable WHERE UserID = 'JoeBloggs' ORDER BY QuestionID DESC
上記のクエリから返された一番上の行は、回答者が最後に回答した質問を示します (QuestionID が質問と同じ順序であった場合)。
そうでない場合は、テーブルへの各回答の日付/時刻を AnswerDate 列に記録し、これを使用できます。
SELECT TOP 1 * FROM AnswersTable WHERE UserID = 'JoeBloggs' ORDER BY AnswerDate DESC
上記のクエリは、JoeBloggs ユーザーに対して最近回答された質問を返します。
編集:以下は、セッション変数を保存および回復するためのテストされていないコードです。コードは、列 InsertionDate、UserID、および SessionVar を持つ UserSessions という名前のデータベース テーブルがあることを前提としています。
UserSessions という名前の SQL テーブルから以前のセッション変数を取得するメソッド。ユーザーのログイン時に呼び出すことができます。
private string GetPreviousSession(string userID)
{
string prevSessionVar = "";
string connectionString = "your connection string to the db goes here";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT TOP 1 SessionVar FROM UserSessions WHERE UserID = @UID ORDER BY InsertionDate DESC", connection))
{
command.Parameters.Add(new SqlParameter("UID", userID));
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
prevSessionVar = reader.GetString(0);
}
}
}
return prevSessionVar;
}
現在のセッション変数を格納するメソッド。Form.Closing イベントで呼び出すことができます。
private void StoreSessionVar(string sessionVar, string userID)
{
string iDate = DateTime.Now.ToString("dd-MMM-yyyy HH:mm:ss");
string connectionString = "your connection string to the db goes here";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO UserSessions (InsertionDate, SessionVar, UserID) VALUES (@IDate, @SessionVarToStore, @UID)", connection))
{
command.Parameters.Add(new SqlParameter("UID", userID));
command.Parameters.Add(new SqlParameter("SessionVarToStore", sessionVar));
command.Parameters.Add(new SqlParameter("IDate", iDate));
SqlDataReader reader = command.ExecuteReader();
}
}
}