我在当前会话中将查询保存到本地数据库时遇到问题。但是,当我关闭应用程序时,数据库已更新。
场景:我有一个登录窗口和注册窗口,当用户注册我有查询将他/她的信息保存到数据库但是在关闭整个应用程序后,它应该将它保存在同一个会话中无需关闭应用程序。
我正在使用此代码进行注册窗口:
private async void button_Click(object sender, RoutedEventArgs e)
{
if (textBox.Text.Length >= 4 && textBox1.Password.Length >= 4)
{
using (var conn = new SqlConnection(@"Data Source"))
using (var cmd = conn.CreateCommand())
{
cmd.CommandText =
"Select Count(*) From Results Where PlayerName = @playerName";
conn.Open();
cmd.Parameters?.Add("@playerName", textBox.Text);
cmd.Parameters?.Add("@Password", textBox1.Password);
var count = (int) cmd.ExecuteScalar();
if (count == 0)
{
cmd.CommandText =
"INSERT INTO LoginInfo (PlayerName, Password) Values (@playerName , @Password)";
cmd.ExecuteNonQuery();
conn.Close();
Close();
}
else
{
label3.Content = "The UserName is already registerd!";
}
}
}
else
{
label3.Content =
"Please Enter Valid information User Name +" +
"and Password should be more than 4 Digits";
}
}
编辑:我使用@displayName
,建议,我看到实际上它已更新,因为当我写相同的信息时,它会让用户已经注册。
Linq to SQL
login window
中可能存在错误,这是我的登录窗口代码:
private void Login_Click(object sender, RoutedEventArgs e)
{
var db = new DataClasses1DataContext();
var userName = from t in db.LoginInfos
select new
{
t.Id,
t.PlayerName,
t.Password
};
foreach (var variable in userName)
{
if (UserName.Text == variable.PlayerName && text_Password.Password == variable.Password)
{
var openChoiceGame = new ChoiceGame(UserName.Text);
textBlock.Text = "The login information are correct ";
openChoiceGame.Show();
using (
var conn =
new SqlConnection(
@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Saif-DevEnv\Source\Workspaces\QuizClashGame\GameQuizClash\Players.mdf;Integrated Security=True;Connect Timeout=30")
)
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "Select Count(*) From Results Where PlayerName = @playerName";
cmd.Parameters.Add("@playerName", UserName.Text);
conn.Open();
var count = (int) cmd.ExecuteScalar();
if (count == 0)
{
// It means it does not exist.
cmd.CommandText = "INSERT INTO Results(PlayerName) VALUES (@playerName)";
cmd.ExecuteNonQuery();
}
conn.Close();
var player = new SoundPlayer(@"C:\Users\Saif-DevEnv\Desktop\SoundRes\switch32.wav");
player.Play();
}
Close();
}
else
{
textBlock.Text = "The login information are not correct ";
}
}
}
登录窗口代码是否有任何错误?
答案 0 :(得分:0)
首先想到:我看到Results
上的ExecutingScalar()在LoginInfo
上的ExecutingNonQuery(),即在两个不同的表上。这是问题吗?
第二个想法:您可以更改插入LoginInfo
的测试方式。这样做是相反的 -
if (cmd.ExecuteNonQuery() == -1)
{
label3.Content = "The UserName is already registerd!";
}
答案 1 :(得分:0)
我没有看到async关键字的任何原因。删除后它应该可以正常工作。
答案 2 :(得分:0)
也许这会有所帮助:Asynchronous Programming
答案 3 :(得分:0)
问题在于$i = 0;
while($row = mysqli_fetch_array($res)){
array_push($result[$i], ($row[0] . $row[1] . $row[2] . $row[3] . $row[4] . $row[5]));
$i++;
}
部分。
但是,我的解决方案是将数据源添加到Linq To Sql
或我的代码中DataContext(@DataSource)
,并使用DataClasses1DataContext(@DataSource);
方法Refresh