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();
}
}
}
}
问题是这样的,我用上面的代码连接数据库,却总是抛出异常,这是为什么啊
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();
}
}
}
}
问题是这样的,我用上面的代码连接数据库,却总是抛出异常,这是为什么啊
处,看看是打开连接报错,还是执行语句时报错。或者把你catch的错误贴出来。
{0}和{1}的外面都加上单引号
'{0}'和'{1}'
用户名 密码 在哪里???