C#中向數據庫中添加注冊新用戶,並查詢數據庫中是否存在同名的用戶。


 

代碼如下: private void button1_Click(object sender, EventArgs e)

        {
         
            SqlConnection conn = new SqlConnection(@"Data Source=SANM\SQLEXPRESS;Initial Catalog=data1220;Integrated Security=True;");
            SqlCommand cmd = new SqlCommand(@"select count(*) from users where name='" + textBox1.Text + "'", conn);  //在數據庫中查找users表中的name字段數據
            SqlCommand cmd2 = new SqlCommand("insert into users values('" + textBox1.Text + "','" + textBox2.Text + "')", conn);//向數據庫data1220庫中的users表中插入數據
            conn.Open();
            int Flag = Convert.ToInt16(cmd.ExecuteScalar());        //將查詢到的數據的類型轉換成int類型的數據
            // ExecuteScalar()方法 返回值的數據類型是Object類型  返回查詢所返回結果的第一行第一列(數據不完整)
            if (Flag == 1)  
            {
                MessageBox.Show("用戶名已經存在!", "提示", MessageBoxButtons.OK);
            }
            else if (textBox2.Text != textBox3.Text)
            {
                MessageBox.Show("兩次輸入的密碼不一致!", "提示", MessageBoxButtons.OK);
            }
            else if (Flag == 0 && textBox2.Text == textBox3.Text)
            {
                int res = cmd2.ExecuteNonQuery();  //返回表中查詢到的所有結果(完整結果)
                if (res == 1)
                {
                    MessageBox.Show("用戶注冊成功!", "提示", MessageBoxButtons.OK);
                }
            }
            conn.Close();
        }
 
代碼運行結果:
        

 

 


免責聲明!

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



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