代碼如下: 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();
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();
}
代碼運行結果:

