using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;namespace 学生在线考试题库
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }        private void button1_Click(object sender, EventArgs e)
        {
            string username = textBox1.Text;
            string password = textBox2.Text;
            string connstring = @"Data Source=LBWIN7\SQLEXPRESS;Initial Catalog=examonline;Integrated Security=True";
            SqlConnection connection = new SqlConnection(connstring);
            string sql = String.Format("select count(*) from User where username={0} and password={1}",username,password);
            try
            {
                connection.Open();
                SqlCommand command = new SqlCommand(sql, connection);
                int num = (int)command.ExecuteScalar();
                if (num > 0)
                {
                    MessageBox.Show("欢迎进入在线考试系统!");
                }
                else
                {
                    MessageBox.Show("你输入的信息有误!");
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("数据库打开失败!");
            }
            finally
            {
                connection.Close();
            }
        }
    }
}
问题是这样的,我用上面的代码连接数据库,却总是抛出异常,这是为什么啊

解决方案 »

  1.   

    本帖最后由 caozhy 于 2011-06-29 00:42:47 编辑
      

  2.   

    在catch块中检查下Exception的具体内容。
      

  3.   

    设断点到connection.Open();
    处,看看是打开连接报错,还是执行语句时报错。或者把你catch的错误贴出来。
      

  4.   

    Data Source=LBWIN7\SQLEXPRESS后面少了.
      

  5.   

    select count(*) from User where username={0} and password={1}
    {0}和{1}的外面都加上单引号
    '{0}'和'{1}'
      

  6.   

    要是别人数据库是int类型的呢!你叫人加了怎么办?这种问题自己细心调试应该是没点问题的啊!
      

  7.   

    where's the DB Login ID & Passwrod?
      

  8.   

    SQL连接字符串有问题,另外这么写代码不安全
      

  9.   

    string connstring = @"Data Source=LBWIN7\SQLEXPRESS;Initial Catalog=examonline;Integrated Security=True";
    用户名 密码 在哪里???