資料層代碼
namespace YNCCommonSystem.DAL
{
public class BaseUserService
{
//根據用戶名查詢用戶資訊
public static DataTable GetUserInfoByUserName(string userName)
{
//建立與資料庫的鏈接
//1.鏈接字串
string connString = @"Data Source=WIN-4JHP4B1TFU4;Initial Catalog=YNCSystem;User ID=sa;Password=**********";
/此處密碼已修改過
//2.根據鏈接字串創建鏈接物件
SqlConnection conn = new SqlConnection(connString);
try
{
//要執行的SQL陳述句
string sql = string.Format(@"select * from [YNCSystem].[dbo].[User] where userName = '{0}'", userName);
//3.打開鏈接
conn.Open();
//執行SQL陳述句取資料
//執行SQL命令
SqlCommand cmd = new SqlCommand(sql,conn);
//取資料到記憶體倉庫
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
//創建臨時倉庫
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
//回傳取到的資料
return ds.Tables[0];
}
catch(Exception ex)
{
throw ex;
}
finally
{
//關閉鏈接
conn.Close();
}
}
}
}
業務邏輯層代碼:
namespace YNCCommonSystem.BLL
{
//用戶表的業務邏輯層
public class BaseUserManager
{
//1.實作系統登錄
public static bool Login(string strLoginName,string strLoginPwd)
{
try
{
//1.呼叫資料訪問層,根據用戶名得到用戶資訊
DataTable dtUser=BaseUserService.GetUserInfoByUserName(strLoginName);
if(dtUser.Rows.Count>0)
{
DataRow drUser = dtUser.Rows[0];
//2.把用戶資訊中的密碼與表示層的密碼進行對比
if(drUser["Code"].Equals(strLoginPwd))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
catch(Exception ex)
{
throw ex;
}
}
}
}
表示層代碼
namespace WinYNC
{
public partial class Formlogin : Form
{
public Formlogin()
{
InitializeComponent();
}
private void label2_Click(object sender, EventArgs e)
{
}
private void btnCancel_Click(object sender, EventArgs e)
{
//關閉表單
//this.Close;
//退出應用程式
DialogResult dr=MessageBox.Show("退出提示", "您確定要退出應用程式嗎?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dr==System.Windows.Forms.DialogResult.Yes)
{
Application.Exit();
}
}
private void btnLogin_Click(object sender, EventArgs e)
{
//呼叫業務邏輯層的登錄方法
bool ret = BaseUserManager.Login(this.tbUserName.Text, this.tbPwd.Text);
if (ret == true)
{
MessageBox.Show("登錄成功!");
}
else
{
MessageBox.Show("登錄失敗!");
}
}
}
}
資料庫:

運行輸入用戶名密碼后顯示登陸失敗,設定斷點后發現在 string connString = @"Data Source=WIN-4JHP4B1TFU4;Initial Catalog=YNCSystem;User ID=sa;Password=**********";出現錯誤,但不知如何修改?
uj5u.com熱心網友回復:
你倒是把報錯內容放出來啊,你試試不用計算機名用ip地址呢uj5u.com熱心網友回復:
看你那表資料選中的后面有空格吧,你定的是nchar型別?你直接在SQL Server Management Studio里查一下試試uj5u.com熱心網友回復:
資料庫的欄位型別改一下,欄位定義要改為varChar,或者向資料庫寫入字串的時候,字串后面加Trim()。如aa.Trim().uj5u.com熱心網友回復:
養成習慣,讀取寫入字串的時候,后面要加上Trim()uj5u.com熱心網友回復:
有關資料庫的問題實在太多,往往錯誤提示資訊距離問題太遠,分析起來太浪費時間,我的弄法是,重新生成資料庫,問題立即解決。然后勤備份資料庫,遇到問題恢復資料庫,若恢復不成功則重新生成資料庫。轉載請註明出處,本文鏈接:https://www.uj5u.com/net/73246.html
標籤:C#
