VS2017 C# winform 項目使用 sqlite (二)


(一)連接數據庫&查詢數據庫,(例子:用戶登錄窗)

        private void BtnLogin_Click(object sender, EventArgs e)
        {
            //登錄檢測
            try
            {
                string dbPath = "Data Source=" + Directory.GetCurrentDirectory() + @"\data\orders.db;Version=3;Password=07762828216;";
                using ( SQLiteConnection conn = new SQLiteConnection(dbPath)) {
                    //查詢是否有相應的數據
                    string uname = TxbUsername.Text.Trim();
                    string upwd = TxbPassword.Text.Trim();
                    string sql_select = "select count(0) from users where username =@uname and password =@upwd ";
                    //連接數據庫
                    if (conn.State == ConnectionState.Closed)
                    {
                        conn.Open();
                    }
                    SQLiteCommand cmd = new SQLiteCommand(sql_select, conn);
                    //cmd.Parameters.Add(new SQLiteParameter("@uname", uname));
                    //cmd.Parameters.Add(new SQLiteParameter("@upwd", upwd));
                    SQLiteParameter[] paras = new SQLiteParameter[] { new SQLiteParameter("@uname", uname), new SQLiteParameter("@upwd", upwd) };
                    cmd.Parameters.AddRange(paras);
                    SQLiteDataReader reader = cmd.ExecuteReader();
                    if (reader.Read())
                    {
                        int result = Convert.ToInt16(reader.GetValue(0));
                        if (result == 0)
                        {
                            MessageBox.Show("用戶名或者密碼錯誤,請重新輸入!"); 
                        }
                        else if(result == 1)
                        {
                            MessageBox.Show("登錄成功!");
                        }
                        else
                        {
                            MessageBox.Show("程序出錯,請不要輸入奇怪的的內容!");
                            //退出軟件
                            System.Environment.Exit(0);
                        }
                    }
                    //關閉數據庫連接
                    reader.Close();
                    conn.Close();
                }
            }
            catch (Exception ex)
            {
               MessageBox.Show("連接數據庫失敗:" + ex.Message);
            }
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM