我在下面的代碼中有用戶登錄表單(用戶名和密碼)我希望它檢查用戶和密碼是否存在於數據庫中但是當輸入用戶和傳遞它不給我訪問form2總是我得到一個錯誤的登錄消息我認爲沒有數據庫的連接或它不讀取if條件?從DB中選擇用戶和密碼的用戶登錄表問題
我的表名是帳戶幷包含兩列(用戶,通過) 數據庫名Database1。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace testdb
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string cs = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;";
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection cn = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("Select * from account where [email protected] and [email protected]", cn);
cmd.Parameters.AddWithValue("@username", textBox2.Text);
cmd.Parameters.AddWithValue("@password", textBox1.Text);
cn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
cn.Close();
int count = ds.Tables[0].Rows.Count;
if (count == 1)
{
Form2 form2 = new Form2();
this.Hide();
form2.Show();
}
else
{
MessageBox.Show("Invalid Login please check username and password");
}
cn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
此行
SqlConnection cn = new SqlConnection(global::testdb.Properties.Settings.Default.Database1ConnectionString);
我改成了
string cs = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;";
注:DB它是在Visual Studio現有意味着我使用它自帶的DB與視覺工作室和我已經定義了用戶名的表帳戶,並通過
這是我的問題,我得到錯誤信息,即使正確的用戶名和密碼 enter image description here
這裏我的數據的基礎上爲VS enter image description here
其他快照可以在我的回覆中發現
您是否嘗試過調試?找到調試器停止的地方,並記下它給你的信息/警告/錯誤。 – Sofver
您總是收到「無效登錄請檢查用戶名和密碼」錯誤信息?如果是,那麼你的數據庫連接工作正常,但如果你收到一些異常消息,那麼在數據庫調用中會出現問題。 –
不知道你的數據是什麼樣的或者你得到了什麼錯誤,它不可能幫助你。請更新您的問題以包含更多詳細信息。 – Ortund