日期:2014-05-18  浏览次数:20897 次

小弟用mysql做数据库做了一个登录界面,可是为什么总是连不上呢?新人学习ing
以下是小弟写的代码:我将登录的select改为Insert又可以成功插入数据库
数据库表结构如下:
mysql> describe account;
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| ID | int(12) | NO | PRI | NULL | auto_increment |
| Username | varchar(50) | NO | | NULL | |
| PW | int(12) | NO | | NULL | |
+----------+-------------+------+-----+---------+----------------+

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace Self
{
  public partial class Login : Form
  {
  public Login()
  {
  InitializeComponent();
  }

  private void btn_login_Click(object sender, EventArgs e)
  {
  MySqlConnection con = new MySqlConnection("Server=localhost;User Id=root;Password=wencui2006;Persist Security Info=True;Database=ken;charset=utf8");
  con.Open();

  string sql = "select count(*) from account where id='"+Convert.ToInt32(tbx_id.Text)+"' and Username='" + this.tbx_user.Text.Trim() + "' and PW='" + Convert.ToInt32(this.tbx_pw.Text.Trim()) + "'";
  // string sql = "insert into account(id,username,pw) values('"+Convert.ToInt32(tbx_id.Text)+"','"+this.tbx_user.Text+"','"+Convert.ToInt32(tbx_pw.Text)+"')";
  MySqlCommand cmd = new MySqlCommand(sql, con);
  int arr = cmd.ExecuteNonQuery();
  if (arr ==1)
  {
  MainForm mform = new MainForm();
  mform.Show();
  this.Hide();
  }
  else
  {
  MessageBox.Show("不存在该用户,请重新输入");
  }
  }

  private void btn_cancel_Click(object sender, EventArgs e)
  {
  this.Close();
  }
  }
}
哪位大侠帮忙看下

------解决方案--------------------
Select count 这样查询
C# code
string sql = "select count(*) from account where id='" + Convert.ToInt32(tbx_id.Text) + "' and Username='" + this.tbx_user.Text.Trim() + "' and PW='" + Convert.ToInt32(this.tbx_pw.Text.Trim()) + "'";
// string sql = "insert into account(id,username,pw) values('"+Convert.ToInt32(tbx_id.Text)+"','"+this.tbx_user.Text+"','"+Convert.ToInt32(tbx_pw.Text)+"')";
MySqlCommand cmd = new MySqlCommand(sql, con);
int count = Convert.ToInt32(cmd.ExecuteScalar());