为什么会出现connection没有初始化的错误提示?

wozuihaole 2012-03-14 11:22:37
问题如题目…………
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 System.Data.SqlClient;

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

private void btnYes_Click(object sender, EventArgs e)
{
string userName = txtName.Text;
string password = txtPwd.Text;
string conString = "Server=.;User ID=sa;Pwd=123;DataBase=student";
SqlConnection connection = new SqlConnection(conString);
string sql = string.Format("select count(*) from [User] where userName='{0}' and password='{1}'",userName,password);
try
{
connection.Open();
SqlCommand command = new SqlCommand();
int num = (int)command.ExecuteScalar();
if (num > 0)
{
MessageBox.Show("欢迎进入成绩管理系统!", "登陆成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
MainForm mainForm = new MainForm();
this.Visible = false;
}
else
{
MessageBox.Show("输入的用户名或者密码错误!", "登陆失败", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,"操作数据库出错!",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
finally
{connection.Close();}
}
}
}
...全文
232 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
anzhiqiang_touzi 2012-05-10
  • 打赏
  • 举报
回复
是因为SqlCommand command = new SqlCommand();改为SqlCommand command = new SqlCommand(sql,connection);就好了
xiaoning8201 2012-04-06
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]
是因为SqlCommand command = new SqlCommand();改为SqlCommand command = new SqlCommand(sql,connection);就好了
[/Quote]

改成这样就可以了。"Server=.;User ID=sa;Pwd=123;DataBase=student";
User ID之间没有空格。
牛哥_ 2012-04-02
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 的回复:]

引用 1 楼 wozuihaole 的回复:
是因为SqlCommand command = new SqlCommand();改为SqlCommand command = new SqlCommand(sql,connection);就好了


[/Quote]
SqlCommand command = new SqlCommand(); 没参数
wozuihaole 2012-03-15
  • 打赏
  • 举报
回复
是因为SqlCommand command = new SqlCommand();改为SqlCommand command = new SqlCommand(sql,connection);就好了

ichenfang163 2012-03-15
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 wozuihaole 的回复:]
是因为SqlCommand command = new SqlCommand();改为SqlCommand command = new SqlCommand(sql,connection);就好了
[/Quote]
这方法好!

1,979

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 其他语言讨论
社区管理员
  • 其他语言社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧