操作数据库遇到的两个小问题

yuekai2008 2009-05-06 02:42:37
一个是获取登录用户的权限;代码为:

string sname = nametb.Text;
string spwd = pwdtb.Text;
if (conn.State == ConnectionState.Closed) { conn.Open(); }
SqlCommand sele = new SqlCommand("", conn);
sele.CommandText = "select 权限 from 管理员表 where 帐号='"+sname+"' and 密码='"+spwd+"'";
int i = sele.ExecuteNonQuery();
textBox1.Text = i.ToString();

textBox1里的值总是为-1,难道我SQL语句有错吗?

另一个是插入数据:

SqlCommand cjietab = new SqlCommand("", conn);
cjietab.CommandText = "insert into 结帐表 "+"values"+"(tbdanhao.Text ,tbtaihao .Text ,tbprice .Text ,stime,cbpeople .Text )";
cjietab.ExecuteNonQuery();

出现的错误是:未处理 System.Data.SqlClient.SqlException
Message="在此上下文中不允许使用名称 \"tbdanhao.Text\"。有效表达式包括常量、常量表达式和变量(在某些上下文中)。不允许使用列名。"
难道这样写是错的吗?请高手指点迷津!
...全文
83 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
yuekai2008 2009-05-06
  • 打赏
  • 举报
回复
多谢大家!
WDFrog 2009-05-06
  • 打赏
  • 举报
回复
建议使用参数化查询
sele.CommandText="insert into 结帐表 values(@tbdanhao ,@tbtaihao ,@tbprice ,@stime,@cbpeople )";
sele.Parameters.AddWithValue("@tbdanhao", tbdanhao.text);
....
直接拼接容易被黑地
wxm3630478 2009-05-06
  • 打赏
  • 举报
回复
[Quote=引用楼主 yuekai2008 的帖子:]
一个是获取登录用户的权限;代码为:

C# code
string sname = nametb.Text;
string spwd = pwdtb.Text;
if (conn.State == ConnectionState.Closed) { conn.Open(); }
SqlCommand sele = new SqlCommand("", conn);
sele.CommandText = "select 权限 from 管理员表 where 帐号='"+sname+"' and 密码='"+spwd+"'";
int i = sele.ExecuteNonQuery();

[/Quote]

同志这里执行的是Select语句 他又没改变任何数据 没有影响到任何行 不是-1是什么
蓝海D鱼 2009-05-06
  • 打赏
  • 举报
回复
pwdtb.Text.Trim(); 防止输入 空格
zealot1021 2009-05-06
  • 打赏
  • 举报
回复
第一个ExecuteNonQuery(),应该用ExecuteScalar(),“ExecuteNonQuery()”是不返回值的,当然是-1。
第 二个应该这么写:

cjietab.CommandText = "insert into 结帐表 "+"values"+"('"+tbdanhao.Text+"' ,'"+tbtaihao .Text+"' ,'"+tbprice .Text+"' ,"+stime+",'"+cbpeople .Text+"' )";
kingtiy 2009-05-06
  • 打赏
  • 举报
回复
int i = sele.ExecuteNonQuery();
返回影响的行数。所以总是-1
应该是select count(*) from where ....
//下面的写法就不对
\cjietab.CommandText = "insert into 结帐表 "+"values"+"(tbdanhao.Text ,tbtaihao .Text ,tbprice .Text ,stime,cbpeople .Text )";
jingsong2008 2009-05-06
  • 打赏
  • 举报
回复
看看这条是不是错了,你这样改试试:cjietab.CommandText = "insert into 结帐表 values (+'"tbdanhao.Text"'+","+'"tbtaihao .Text'" +","+'"tbprice .Text"'+","+'"stime"'+","+'"cbpeople .Text"' )";

111,126

社区成员

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

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

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