当我运行我的应用程序时,它会很好地结束,但是当我之后检查我的数据库时,它从不显示任何数据。这是我的代码:
private void button1_Click(object sender, EventArgs e)
{
string saltedcryps = saltpassword(10);
string passWithSalt = (textBox1.Text + saltedcryps);
string hashedResult = hashPassAndSalt(passWithSalt);
if (checkPasswordsMatch() == "B")
{
SqlCeConnection myConnection = new SqlCeConnection("Data Source = pwdb.sdf");
try
{
myConnection.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
SqlCeCommand myCommand = new SqlCeCommand("INSERT INTO PW Values ('Master', '" + saltedcryps + "', '" + hashedResult + "');", myConnection);
myCommand.ExecuteNonQuery();
myConnection.Close();
this.Hide();
}
}
private string checkPasswordsMatch()
{
if (textBox1.Text == "")
{
MessageBox.Show("Passwords cannot be empty");
return "A";
}
else
{
MessageBox.Show(textBox1.Text == textBox2.Text ? "Thanks for registering!" : "Your passwords do not match");
return "B";
}
}
private string saltpassword(int size)
{
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
byte[] buff = new byte[size];
crypto.GetBytes(buff);
return Convert.ToBase64String(buff);
}
private string hashPassAndSalt(string passWithSalt)
{
HashAlgorithm hashAlg = new SHA256CryptoServiceProvider();
byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(passWithSalt);
byte[] bytHash = hashAlg.ComputeHash(bytValue);
string base64 = Convert.ToBase64String(bytHash);
return base64;
}
}
问题所在的是button1_Click。当它运行myCommand.ExecuteNonQuery();它永远不会抛出异常,它只会继续,而不会实际输入任何信息......
任何人都有线索?
答案 0 :(得分:0)
试试这个:
if (checkPasswordsMatch() == "B")
{
SqlCeConnection myConnection = new SqlCeConnection("Data Source = pwdb.sdf");
try
{
myConnection.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
SqlCeCommand myCommand = myConnection.CreateCommand();
myCommand.CommandType = CommandType.Text;
myCommand.CommandText = "INSERT INTO PW Values ('Master', '" + saltedcryps + "', '" + hashedResult + "');"
myCommand.ExecuteNonQuery();
myConnection.Close();
this.Hide();
}
如果这不起作用,请尝试将绝对路径放在连接字符串上。
答案 1 :(得分:0)
该连接字符串看起来不正确;除非你做的事非常奇怪,否则你应该使用Data Source=|DataDirectory|pwDB.sdf
。
为什么您认为您的数据库“从不显示任何数据”?你在哪里寻找数据?在项目目录中的原始源数据中?这几乎肯定是错的;在部署应用程序时,您没有部署源代码,不是吗?您需要查看部署文件夹,请参阅this answer。
答案 2 :(得分:0)
将try catch放在ExecuteNonQuery周围,这样你就可以看到什么是异常,否则必须是你的连接字符串(DataSource = pwDB.sdf看起来不对我)必须有用户ID;密码; dataSource =您的IP和初始目录:
SqlCommand Command = new SqlCommand(YourQuery,myConnection);
myConnection.Open();
int Rows=0;
try
{
Rows = Command.ExecuteNonQuery();
myConnection.Close();
}
catch (Exception ex)
{
conSMS.Close();
string Msg = ex.Message;
//I log my exceptions
//Log("ERROR: "+RemoveSQ(Query));
//Log(RemoveSQ(Msg));
}
//check Rows here if there is no exception