我仍然了解Windows窗体,在form1上,我拥有用户控件。 但是在我的form3上,我想显示类似Hi User…的内容,并且在我的sql表中,我具有登录用户的“用户名”,“密码”和“名称”,但是我不知道如何!
提取登录代码:
private void button3_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConnectionString);
SqlDataAdapter sda = new SqlDataAdapter($"Select Count(*) from [Table] Where username = '{textBox1.Text}' and password ='{textBox2.Text}'", selectConnection: con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
Form2 ss = new Form2();
ss.Show();
}
else
{
MessageBox.Show("Username or password incorrect, try again!.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
如果有人可以帮助我,我真的很感谢我,对我的英语感到抱歉。
答案 0 :(得分:0)
请记住,葡萄牙语中存在堆栈溢出问题:https://pt.stackoverflow.com/
无论如何,希望这对您有所帮助。
在本解释的结尾,我将更改所有逻辑,但是只是为了使某些观点更容易一点一点地理解。因此,首先使SQL连接成为使用块,如下所示:(这样做,您无需手动关闭连接并放置对象。)
using(SqlConnection con = new SqlConnection(ConnectionString))
{
using(SqlDataAdapter sda = new SqlDataAdapter($"Select Count(*) from [Table] Where username = '{textBox1.Text}' and password ='{textBox2.Text}'", selectConnection: con))
{
DataTable dt = new DataTable();
sda.Fill(dt);
}
}
为避免SQL注入使用类似以下内容来使查询参数化:
using(SqlDataAdapter sda = new SqlDataAdapter($"Select Count(*) from [Table] Where username =@username and password =@username, selectConnection: con))
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "@username";
parameter.Value = "xyz";
// code: same to the password.....
无论如何都不要在ButtonClick事件中使用SQL连接逻辑。为此创建一个方法,只需调用它;
正如我在第一个解释中所说,让它更具可读性,所以请执行以下操作:
using(SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
using(SqlCommand command = new SqlCommand("Select Count(*) from [yourTable] Where username=@username and password=@username", conn))
{
command.Parameters.AddWithValue("@username","theusername");
command.Parameters.AddWithValue("@password","thepassword");
// int result = command.ExecuteNonQuery();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
MessageBox.Show(String.Format("Hi {0}",reader["username"]));
}
}
}
}