C#窗体连接数据库的问题(新手求教!)

北野语冰 2014-05-26 06:38:19
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 name=this.textBox1.Text;
String password=this.textBox2.Text;
//获得数据库连接字符串
String coon = @"Data Source=JJ\SQLEXPRESS;Initial Catalog=jonas;Integrated Security=True";
//创建sqlconnection 对象
SqlConnection connection=new SqlConnection(coon);
String sql=String.Format("select count(8) from Login where username='0',and password='1'",name,password);

// 创建sqlcommand对象
SqlCommand command=new SqlCommand(sql,connection);
connection.Open();
int num = Convert.ToInt32(command.ExecuteScalar());
try
{
if(num>0)
{
MessageBox.Show("登陆成功!");
}
else
{
MessageBox.Show("登陆失败!");

}
}
catch (Exception ex)
{

MessageBox.Show("异常错误"+ex);
}
finally
{
connection.Close();
}
}
}
}
这些是我从视频上学习的,但是在点击登录的时候是错的,提示:
System.Data.SqlClient.SqlException”类型的未经处理的异常在 System.Data.dll 中发生;
奇怪?是数据库权限不够还是什么?望大神指点一下....
后来试着把 int num = Convert.ToInt32(command.ExecuteScalar());
放进try里面 点登录又提示
...全文
134 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
shareri 2014-05-26
  • 打赏
  • 举报
回复

String sql=
串的格式不对
smthgdin_020 2014-05-26
  • 打赏
  • 举报
回复
String sql=String.Format("select count(8) from Login where username='0',and password='1'",name,password); format这里不是这样子的。参数要用{Index}包起来,里面Index,对应后面的实际参数值。
我现在在路上 2014-05-26
  • 打赏
  • 举报
回复
楼上对的,初学看下视频教程挺不错的,一定要多练,前提是你把大概原理理解了
wind_cloud2011 2014-05-26
  • 打赏
  • 举报
回复
String sql = String.Format("select count(*) from Login where username='{0}' and password='{1}'",name,password);
wind_cloud2011 2014-05-26
  • 打赏
  • 举报
回复
你的sql串写得不对

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

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